首页 > 解决方案 > How to add the CSS to content page only on clicking of a button from an extension?

问题描述

I just wanted to know if there is a way to inject a css file into a page only on the click of a button from a chrome extension. Also possibly to remove the css injected once the button in the extension is clicked again.

  1. Manifest.json
{
   "manifest_version": 2,
   "name": "KS Scrapper",
   "description":"Simple Scrapper",
   "version" : "1.0.0",
   "icons":{"128":"images/ks_logo_128.png"},
   "browser_action" : {
       "default_icon" : "images/ks_logo_19.png",
       "default_popup" : "popup.html"
   },
   "content_scripts" : [
           {
           "matches": ["<all_urls>"],
           "js" : ["jquery-2.1.4.min.js", "content.js"],
           "css" : ["c.css"]
       }
   ],
   "web_accessible_resources": [
       "css/style.css",
       "c.css"
   ],
   "permissions": ["tabs"],
   "background":{
       "scripts":["background.js"]
   }
}

I'm adding c.css to the into the content script and it does it job but I wanted to know if there is any way to toggle between when it is active and when it isn't using a button. If I have made any errors please correct me. Thanks

标签: javascriptgoogle-chrome-extensiongoogle-chrome-devtools

解决方案


不要css在 manifest.json 中注入,而是link在页面本身中创建一个具有特殊 id 的元素,以便您以后可以使用标准 DOM 方法删除该元素。

清单.json:

  • content_scripts此任务不需要部分
  • "permissions": ["activeTab"],不需要tabs这个任务

popup.js,在一些click监听器中:

chrome.tabs.executeScript({file: 'toggle-style.js'})

切换样式.js:

(() => {
  const id = chrome.runtime.id;
  let el = document.getElementById(id);
  if (el) {
    el.remove();
  } else {
    el = document.createElement('link');
    el.id = id;
    el.rel = 'stylesheet';
    el.href = chrome.runtime.getURL('c.css');
    document.head.appendChild(el);
  }
})();

推荐阅读