如何通过Chrome扩展将CSS注入网页?

发布于 2024-12-07 06:36:02 字数 766 浏览 1 评论 0原文

我不知道如何通过 Chrome 扩展将 CSS 注入网页。我正在尝试将其注入网页:

body {
   background: #000 !important;
}

a {
   color: #777 !important;
}

这是我的manifest.json:

{
"update_url":"http://clients2.google.com/service/update2/crx",
  "name": "Test Extension",
  "version": "1.0",
  "description": "This is a test extension for Google Chrome.",
  "icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },
  "background_page": "background.html",
  "browser_action": {
    "default_icon": "icon19.png"
  },
  "content_scripts": [
    {
      "matches": ["http://test-website.com/*"], 
      "js": ["js/content-script.js"]
    }
  ],

    "permissions": [ "tabs", "http://test-website.com/*" ]

}

I do not know how to inject CSS into a webpage through a Chrome extension. I am trying to inject this into a web page:

body {
   background: #000 !important;
}

a {
   color: #777 !important;
}

Here is my manifest.json:

{
"update_url":"http://clients2.google.com/service/update2/crx",
  "name": "Test Extension",
  "version": "1.0",
  "description": "This is a test extension for Google Chrome.",
  "icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },
  "background_page": "background.html",
  "browser_action": {
    "default_icon": "icon19.png"
  },
  "content_scripts": [
    {
      "matches": ["http://test-website.com/*"], 
      "js": ["js/content-script.js"]
    }
  ],

    "permissions": [ "tabs", "http://test-website.com/*" ]

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

假情假意假温柔 2024-12-14 06:36:02

您可能必须在清单文件中添加额外的行:

"content_scripts": [
    {
      "matches": ["http://test-website.com/*"], 
      "js": ["js/content-script.js"],
      "css" : ["yourcss.css"]
    }
],

"css": ["..."] 中定义的 CSS 文件将添加到与中提到的位置匹配的每个页面中匹配

如果您正在开发 Chrome 扩展程序,请确保查看以下页面:

  1. 开发人员指南

You can have to add an extra line in your manifest file:

"content_scripts": [
    {
      "matches": ["http://test-website.com/*"], 
      "js": ["js/content-script.js"],
      "css" : ["yourcss.css"]
    }
],

The CSS file as defined in "css": ["..."]will be added to every page which matches the location as mentioned in matches.

If you're developing a Chrome extension, make sure that you have a look at these pages:

  1. Developer's guide
蓝戈者 2024-12-14 06:36:02

您还可以使用 Chrome Tabs API 网页

chrome.tabs.insertCSS(integer tabId, object details, function callback);

当然,您首先需要目标选项卡的 ID。

Chrome 扩展文档没有讨论如何解释注入的 CSS,但事实是,通过此方法或通过将其包含在清单中注入到网页的 CSS 文件被解释为用户样式表。

在这方面,值得注意的是,如果您确实使用这些方法注入样式表,它们将在一个关键方面受到限制(至少从 Chrome v.19 开始):Chrome 忽略“用户样式表中的“!important”指令。您注入的样式规则将被页面中包含的任何内容所取代。

如果您想避免注入内联样式规则,一种解决方法如下(我使用 jQuery 进行实际插入,但可以直接使用 Javascript 完成):

$(document).ready(function() {
var path = chrome.extension.getURL('styles/myExtensionRulz.css');
$('head').append($('<link>')
    .attr("rel","stylesheet")
    .attr("type","text/css")
    .attr("href", path));
});

然后您可以将样式表放入扩展程序的 styles 文件夹中,但您不需要将其列在清单上的任何位置。上面的相关部分是,您将使用 chrome API 来获取样式表的 URL,然后将其作为链接的 href 值插入。现在,您的样式表将获得更高的优先级,并且您可以在需要时使用“!important”指令。

这是在最新版本的 Chrome 中唯一适合我的解决方案。

You can also inject a css file into one or more tab's content by using the following syntax as detailed on the Chrome Tabs API webpage:

chrome.tabs.insertCSS(integer tabId, object details, function callback);

You will first need the ID of your target tab, of course.

The Chrome Extension documentation doesn't discuss how the injected CSS is interpreted, but the fact is that CSS files that are injected into a webpage, by this method or by including them in the manifest, are interpreted as user stylesheets.

In this respect, it is important to note that if you do inject stylesheets by using these methods, they will be limited in one crucial way ( at least, as of Chrome v.19 ): Chrome ignores "!important" directives in user stylesheets. Your injected style rules will be trumped by anything included in the page as it was authored.

One work-around, if you want to avoid injecting inline style rules, is the following (I'm using jQuery for the actual insertion, but it could be done with straight Javascript):

$(document).ready(function() {
var path = chrome.extension.getURL('styles/myExtensionRulz.css');
$('head').append($('<link>')
    .attr("rel","stylesheet")
    .attr("type","text/css")
    .attr("href", path));
});

You can then put the stylesheet in your extension's styles folder, but you won't need to list it anywhere on the manifest. The relevant part above is that you will use the chrome API to get your stylesheet's URL, then plug that in as the link's href value. Now, your stylesheet will be given a higher precedence, and you can use the "!important" directive where needed.

This is the only solution that works for me in the latest version of Chrome.

知你几分 2024-12-14 06:36:02

看起来 chrome.tabs.insertCSS 已被弃用。您应该使用:

https://developer.chrome.com/docs/extensions/参考/脚本/

let [tab] = await chrome.tabs.query({
    active: true,
    currentWindow: true
});

chrome.scripting.insertCSS({
        target: {
            tabId: tab.id
        },
        files: ["button.css"],
    },
    () => {
        chrome.scripting.executeScript({
            target: {
                tabId: tab.id
            },
            function: doSomething,
        });
});

Looks like chrome.tabs.insertCSS is deprecated. You should be using:

https://developer.chrome.com/docs/extensions/reference/scripting/

let [tab] = await chrome.tabs.query({
    active: true,
    currentWindow: true
});

chrome.scripting.insertCSS({
        target: {
            tabId: tab.id
        },
        files: ["button.css"],
    },
    () => {
        chrome.scripting.executeScript({
            target: {
                tabId: tab.id
            },
            function: doSomething,
        });
});
生来就爱笑 2024-12-14 06:36:02

这并不难。你可以使用这个:

{
  "update_url": "http://clients2.google.com/service/update2/crx",
  "name": "Test Extension",
  "version": "1.0",
  "description": "This is a test extension for Google Chrome.",
  "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" },
  "background_page": "background.html",
  "host_permissions": ["*://test-website.com/*"],
  "browser_action": {
    "default_icon": "icon19.png"
  },
  "content_scripts": [
    {
      "matches": ["http://test-website.com/*", "https://test-website.com/*"],
      "js": ["js/content-script.js"],
      "css": ["css/styles.css"]
    }
  ]
}

It's not that hard. you can use this:

{
  "update_url": "http://clients2.google.com/service/update2/crx",
  "name": "Test Extension",
  "version": "1.0",
  "description": "This is a test extension for Google Chrome.",
  "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" },
  "background_page": "background.html",
  "host_permissions": ["*://test-website.com/*"],
  "browser_action": {
    "default_icon": "icon19.png"
  },
  "content_scripts": [
    {
      "matches": ["http://test-website.com/*", "https://test-website.com/*"],
      "js": ["js/content-script.js"],
      "css": ["css/styles.css"]
    }
  ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文