Home > Article > Web Front-end > Why Is My Injected CSS Not Applying in My Content Script?
Troubleshooting CSS Injection Failure in Content Scripts
In content scripts, injecting CSS can sometimes prove challenging. Let's delve into a common issue where the injected CSS fails to appear on the webpage.
Problem Statement:
A user is encountering problems injecting a CSS file ("myStyles.css") through a content script, despite including it in the "css" array of the manifest.json file.
Manifest Excerpt:
{ "content_scripts": [ { "matches": [ "http://*/*", "https://*/*", "file:///*/*"], "css": ["myStyles.css"], "js": ["myScript.js"], "all_frames": true } ] }
Possible Causes:
Even though the stylesheet is injected, it may not be applied due to factors such as:
Solutions:
To resolve this issue, consider the following options:
1. Increase CSS Rule Specificity
Enhance the specificity of the CSS rules in "myStyles.css" to ensure their precedence.
2. Utilize "Important" Declaration
Append "!important" to each CSS rule in "myStyles.css" to force their application.
#test { margin: 0 10px !important; background: #fff !important; padding: 3px !important; color: #000 !important; }
3. Inject CSS via Content Script
Alternatively, inject the CSS dynamically through JavaScript in "myScript.js":
var style = document.createElement('link'); style.rel = 'stylesheet'; style.type = 'text/css'; style.href = chrome.extension.getURL('myStyles.css'); (document.head||document.documentElement).appendChild(style);
Manifest Modification:
Ensure the "web_accessible_resources" key is included in manifest.json (for manifest version 2), allowing the "myStyles.css" file to be accessible from non-extension pages.
{ "web_accessible_resources": ["myStyles.css"] }
By implementing these solutions, you can effectively resolve the issue of CSS injection failure and ensure that injected styles are applied as intended.
The above is the detailed content of Why Is My Injected CSS Not Applying in My Content Script?. For more information, please follow other related articles on the PHP Chinese website!