Chrome扩展程序的浏览器操作,带有弹出窗口,可以注入/删除CSS

时间:2017-07-18 14:54:56

标签: google-chrome-extension

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

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

相关问题