【问题标题】:Chrome extension - inject css to pages upon browser action clickedChrome 扩展 - 在浏览器操作单击时将 css 注入页面
【发布时间】:2012-12-11 03:06:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

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

    ma​​nifest.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 一样,您需要指定适当的规则来覆盖页面的规则才能看到更改,这在大多数情况下意味着在您的 CSS 中使用 important! 标记。

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2016-06-13
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多