首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用content.js [CHROME扩展]注入自定义CSS不起作用

问用content.js [CHROME扩展]注入自定义CSS不起作用
EN

Stack Overflow用户
提问于 2022-03-13 09:04:13
回答 1查看 569关注 0票数 0

我创建了一个铬的扩展,以改变一些网站的默认字体。

manifest.json

代码语言:javascript
复制
{
  "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

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2022-03-13 11:37:00

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

如果您想让用户在任何时候启用/禁用样式表,动态添加样式表是个好主意。例如,使用选项页。

manifest.json

代码语言:javascript
复制
{
  "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 (内容脚本)

代码语言:javascript
复制
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");
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71455272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档