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

yebdmbv4  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(121)

我创建了一个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

7vux5j2d

7vux5j2d1#

如果您想从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");
}

相关问题