2

我知道如何使用这种方法将 CSS 注入指定的 URLs https://stackoverflow.com/a/7619104/1157283

但是,如果我只想在单击浏览器操作时将其注入这些页面怎么办?我正在阅读有关编程注入http://developer.chrome.com/extensions/content_scripts.html#pi的内容,这使得您似乎必须获取要注入 CSS 的所有页面的 tabID,然后循环遍历它们以为每个 tabID 注入 CSS?

这是需要的还是我在这里完全不合时宜?看起来它应该比我建议的更直接。谢谢!

4

1 回答 1

3

不要害怕我的朋友,这是解决您问题的正确方法。

manifest.json 我们将指定要注入 css 的 url,以及权限指令中的选项卡。

"permissions":[
  "tabs",
  "https://google.com.mx/*"
],

background.js 添加正确的 onClick 监听器。

chrome.browserAction.onClicked.addListener(browserListener);

听众看起来像这样

var browserListener = function(tab) {
    var regexPage = new RegExp(/https:\/\/www.google.com.mx\//); // We use a regular expresion to check which page was given.
    var match = regexPage.exec(tab.url); // We then check if the given page matches our expression.
    // If it matches and the status of the tab is complete...
    if(match && tab.status === 'complete') {
        //We insert the css
        chrome.tabs.insertCSS(tab.id, {
            file: "css/test.css"
        });
    }
}

如果您https://*/*在权限指令中请求对所有页面的权限,则可以跳过匹配部分。这使您对内容脚本具有更大的灵活性,它们仅通过匹配来触发;请记住,与任何 CSS 一样,您需要指定适当的规则来覆盖页面的规则以查看更改,这在大多数情况下意味着important!在您的 CSS 中使用标签。

于 2012-12-24T23:16:42.310 回答