How to import CSS using the Chrome plugin inject

How to import CSS in Chrome plugin injection

How to import CSS in Chrome plugin injection

When developing Chrome plugins, we usually need to add a custom CSS file to the plugin’s popup page or content. Scripts can be used to import stylesheets to enhance the interface or achieve specific styling effects. However, when developing Chrome extensions, you can’t directly import CSS files using the link tag in the HTML file like in standard web development. Instead, you need to dynamically inject CSS files into the page using JavaScript. This article will detail how to use inject to import CSS files in Chrome extensions.

Step 1: Declare permissions in manifest.json

First, declare permissions in the extension’s manifest.json file to allow the extension to inject CSS into the page. Add the following code to the manifest.json file:


{ 
"manifest_version": 2, 
"name": "My Chrome Extension", 
"version": "1.0", 
"permissions": [ 
"activeTab" 
], 
"content_scripts": [ 
{ 
"matches": [ 
"" 
], 
"css": [ 
"styles.css"
]
}
]
}

In the above code, we declare the plugin name and version number and add the activeTab permission in the permissions field to make it effective in the current tab. Furthermore, in the content_scripts field, we use "matches": [""] to match all pages and include the styles.css file using "css": ["styles.css"].

Step 2: Create a CSS File

Next, create a CSS file named styles.css in the plugin’s root directory and add the required style code. For example, we could add the following code to styles.css:

body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}

h1 {
color: blue;
}

The above code will set the page’s background color to light gray, the font to Arial or sans-serif, and the h1 heading color to blue.

Step 3: Use inject to inject the CSS file

Finally, we need to use the chrome.tabs.insertCSS method in the Chrome plugin’s JavaScript file to inject the CSS file into the page. Add the following code to the plugin’s JavaScript file:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.insertCSS(tabs[0].id, {file: "styles.css"}); 
}); 

In the above code, we use the chrome.tabs.query method to obtain the currently active tab information and use the chrome.tabs.insertCSS method to inject the styles.css file into the current tab.

Sample Code Results

After adding the code to the Chrome extension and loading it, you’ll see the background color of the webpage change to light gray, the font to Arial or sans-serif, and the H1 heading color change to blue.

Through the above steps, you can successfully import the CSS file into the Chrome extension and customize the page style.

Leave a Reply

Your email address will not be published. Required fields are marked *