javascript - 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.
- 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
解决方案
不要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);
}
})();
推荐阅读
- python - 是否可以在与 seaborn 的配对图中将 KDE 估计添加到 hisgram?
- c++ - AVX:“如果不为零,则为 1”
- blazor-client-side - 如何在 Blazor Webassembly 中使用“Sec-Fetch-Mode: no-cors”请求 http 请求
- javascript - Javascript:将播放器添加到数组中的特定对象
- c++ - 我正在尝试使用 C++ 通过空格分割字符串,其中来自数据库的数据
- office-js - 如何重现特定的 365 加载项问题(在 OWA 与桌面客户端上返回不同的电子邮件)
- c# - Cosmos 数据库所需的数据库实体(模型)
- oracle - 在 oracle 中加密解密 PL SQL 包
- hybris - Spartacus 商店前台在点击 localhost:4200 时返回空白页面。正在加载网页标题,但没有加载来自 CMS 的内容
- typescript - 有没有办法在 VS Code for TypeScript 中强制执行类型定义?