【问题标题】:Chrome Extension's browser action with a popup that inject/delete CSSChrome 扩展的浏览器操作,带有注入/删除 CSS 的弹出窗口
【发布时间】:2017-12-23 12:42:23
【问题描述】:

我想通过chrome扩展的浏览操作弹出窗口来询问一种注入css或删除注入css的方法。我试图通过几个地方来了解如何做到这一点,但我无法理解它们。

我想制作类似于"A browser action with a popup that changes the page color" 的扩展名,但单击popup.html 中的div 以加载或卸载创建的css 文件。

这是我目前的工作 (https://github.com/Zhekoay/Self-Custom-Dark-Theme),它使用内容脚本直接插入 css。现在我想让它能够以不同的方式加载或卸载,而不是一次性加载全部。

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    Chrome API 无法移除通过 manifest.json 注入的 CSS。

    demo extension 一样注入代码,但使用带有内容脚本名称的file 参数,它将添加或删除(如果存在)document.documentElement 下的link 元素和@ 987654327@ 等于 chrome.runtime.idhref 指向一个 web accessible CSS 文件。

    1. 从 manifest.json 中删除 "content_scripts"
    2. "web_accessible_resources": ["*.css"] 添加到 manifest.json
    3. 在 popup.js 中为 div 添加点击处理程序
    4. 在点击处理程序中:chrome.tabs.executeScript({file: 'content.js'});
    5. content.js:

      (function() {
        var styleElement = document.getElementById(chrome.runtime.id);
        if (styleElement) {
          styleElement.remove();
          return;
        }
        var css = ({
          'www.youtube.com': 'app_yt_HoveredImg.css',
          'www.messenger.com': 'fb_messenger_styles.css',
          'www.google.com': 'google_styles.css',  
          'translate.google.com': 'google_styles.css',
          'apis.google.com': 'google_styles.css',
        })[location.hostname];
        if (!css) {
          return;
        }  
        styleElement = document.createElement('link');
        styleElement.id = chrome.runtime.id;
        styleElement.rel = 'stylesheet';
        styleElement.href = chrome.runtime.getURL(css);
        document.documentElement.appendChild(styleElement);
      })();
      

    注意,在此工作流程中,您只需要 "permissions": ["activeTab"] 而不是 "tabs":优点是 activeTab 在安装扩展程序时不会请求权限。

    【讨论】:

    • 在应用您的解决方案时解决了一些愚蠢的错误后,它终于起作用了。谢谢。我可以进一步询问是否有办法对此进行检查或调试?
    • 在 content.js 中添加debugger; 并在网页上打开 devtools:当脚本被注入时,devtools 调试器将被激活。至于弹出窗口,它有自己的开发工具:右键单击弹出窗口,然后单击检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 2014-11-02
    • 2016-06-13
    相关资源
    最近更新 更多