CSS Injection Issues in Content Scripts for Extensions
Despite defining CSS injection in the manifest, your CSS file remains absent from the webpage. Here are the possible causes and solutions:
Reason: Conflicting CSS Rules
The style sheet is injected but not applied due to other styles overriding its rules.
Solution:
Reason: Content Script Injection Limit
Manifest version 3 limits content scripts from directly injecting CSS.
Solution: Inject CSS via a content script as follows:
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.json:
"web_accessible_resources": ["myStyles.css"]
Note: When using Manifest version 2, the "web_accessible_resources" key is required to allow access to the CSS file from a non-extension page.
The above is the detailed content of Why Am I Unable to Inject CSS into Webpages Using Content Scripts for Extensions?. For more information, please follow other related articles on the PHP Chinese website!