我发现了另一个问题,但没有找到答案。我很想做同样的事情。
但是这个问题的答案不会永久更改样式表,因为在页面重新加载时,样式表将被恢复并且没有任何更改。
For a Google Chrome extension, how do I define a stylesheet toggle within the Popup?
When a user clicks on the browser icon for the extension, it brings up the Popup that has been defined.
I need to create a toggle button to turn on/off a stylesheet for a specific page/domain when a user clicks a button that is within the popup.
For example, when a user uses the Adblock extension, when the user clicks the browser icon, it brings up the popup, which has a series of links. One such link is "don't run on this page", which then changes to "enable" which the user can click to turn it back on.
Another example (much better example): Classic Popup blocker has a button on the popup that says "add this page to blacklist" and once clicked changes to "remove from blacklist".
image1 i.stack.imgur.com/92gVx.jpg
image2 i.stack.imgur.com/Xvyyp.jpg
这是我当前在 HTML 文件中的内容。这样就有一个简单的复选框,如果选中它就会运行 javascript:
<script type="text/javascript">
$("#button").click(function(){
chrome.extension.sendRequest({ msg: "toggle" });
});
</script>
<input type="checkbox" checked="checked" id="button" /> TOGGLE IT
最佳答案
您可以基于某种切换来进行注入(inject),而不是基于用户交互来注入(inject)。只需为 chrome.tabs.onUpdated
事件添加一个监听器,并过滤它以查找您想要受影响的网站,然后在您的切换设置为 true 时注入(inject) css。例如:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
//assuming `cssToggle` is defined
if(tab.url && cssToggle == "true"){
// assuming `url` is the url you want to change
if(tab.url.indexOf(url) >-1)
chrome.tabs.insertCSS(tabId, {file:"style.css", runAt: "document_start"});
}
});
使用选项页面切换样式表的示例:
manifest.json
"options_page": "options.html",
options.html
<script src="options.js"></script>
[...]
<select id="cssSelect">
<option value="true">Enabled</option>
<option value="false">Disabled</option>
</select>
options.js
$('#cssSelect').change(function(){
chrome.runtime.sendMessage({method: 'setCSS', css:$(this).val()});
});
背景.js
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.method == 'setCSS')
cssToggle = message.css;
});
请原谅 jQuery,这就是我使用的,我不想将其转换为纯 JS 并给你错误的代码。因此,我在 list 中定义了一个选项页面,在该选项页面上我有一个带有启用/禁用选项的选择。当它改变时,我将新值发送到我的后台页面并相应地更新 cssToggle
var。请注意,我现在正在针对字符串进行测试,因为这是我在消息中发送的内容,并且它只会减少代码。
就具有多种样式切换而言。如果只是几个,那么你可以只拥有这个的倍数,但如果超过这个,我建议做一些不同的事情。也许将其定义为一个包含 url、toggle 和要注入(inject)的文件的对象数组,如下所示:
[{url:url1,toggle:toggle1,file:file1},{url:url2, toggle:toggle2, file:file2},...]
关于javascript - 如何设置永久禁用/启用 Chrome 扩展样式表的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16128599/