使用content.js[CHROME EXTENSION]注入自定义CSS不起作用



我创建了一个chrome扩展,用于更改一些网站的默认字体。

manifest.json

{
"name": "Custom Font",
"version": "0.0.1",
"description": "A Extension to change default Fonts.",
"manifest_version": 3,
"content_scripts": [
{
"matches": ["https://dev.to/*", "https://github.com/*"],
"js": ["main.js"] // content.js
}
]
}

main.js

const head = document.head || document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.rel = 'stylesheet';
if (window.location.href.includes('https://dev.to')) {
link.href = chrome.runtime.getURL('devTo.css');
}
if (window.location.href.includes('https://github.com')) {
link.href = chrome.runtime.getURL('github.css');
}
head.appendChild(link);

但是当我试图在上面提到的网站上运行上面的代码时,它给了我一个错误:

GET chrome-extension://invalid/ net::ERR_FAILED

如果您想从JavaScript内容脚本(在Chrome扩展清单v3中(动态添加样式。你可以这样做:

如果您想让用户随时选择启用/禁用样式表,那么动态添加样式表是个好主意。例如,使用选项页面。

manifest.json

{
"name": "Inject Style",
"action": {},
"manifest_version": 3,
"version": "0.1",
"description": "Inject the stylesheet from content script",
"content_scripts": [
{
"matches": ["https://dev.to/*", "https://github.com/*"],
"js": ["main.js"]
}
],
"permissions": ["activeTab"],
"host_permissions": ["<all_urls>"],
"web_accessible_resources": [
{
"resources": [ "devTo.css"],
"matches": [ "https://dev.to/*" ]
},
{
"resources": [ "github.css"],
"matches": [ "https://github.com/*" ]
}
]
}

main.js(内容脚本(

function addstylesheet(filename){
var link = document.createElement("link");
link.href = chrome.runtime.getURL(filename);
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}

if(window.location.href.match(/(https://(.*github.com/.*))/i)) {
addstylesheet("github.css");
} else if(window.location.href.match(/(https://(.*dev.to/.*))/i) {
addstylesheet("devTo.css");
}

最新更新