如何从每个页面的后台页面运行chrome.tabs.insertCSS? [英] How to run chrome.tabs.insertCSS from the background page on each page?

查看:305
本文介绍了如何从每个页面的后台页面运行chrome.tabs.insertCSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在没有内容脚本的页面 中添加自定义样式表.我的CSS可以,但是使用onUpdatedonCreated事件侦听器的以下代码不起作用.

I'd like to add a custom style sheet in a page without a content script. My CSS is OK, but the code below, using the onUpdated and onCreated event listeners do not work.

manifest.json的一部分:

"permissions": [
      "http://www.site_domain.com/*",
      "tabs"],

background.html :

background.html:

chrome.tabs.onUpdated.addListener(function (tab) {
    var tabUrl = tab.url;
    if (tabUrl.indexOf("site_domain") != -1) {
        changeBgkColor();
    }
});

chrome.tabs.onCreated.addListener(function (tab) {
    var tabUrl = tab.url;
    if (tabUrl.indexOf("site_domain") != -1) {
        changeBgkColor();
    }
});

function changeBgkColor(){
    chrome.tabs.insertCSS(null, {file:"css/styles.css"})
};

推荐答案

chrome.tabs.onCreate必须替换为

chrome.tabs.onCreate has to be replaced with chrome.tabs.onCreated (with a d!).

解决此问题后,最好将tabId传递给 chrome.tabs.insertCSS 方法.另外,通过合并事件侦听器来减少代码重复:

After fixing this, you'd better pass a tabId to the chrome.tabs.insertCSS method. Also, reduce the code repetition by merging the event listeners:

chrome.tabs.onCreated.addListener(do_something);
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    if (info.status == 'complete') do_something(tab);
});

function do_something(tab) {
    var tabUrl = tab.url;
    if (tabUrl && tabUrl.indexOf("site_domain") != -1) {
        // changeBgkColour() here:
        chrome.tabs.insertCSS(tab.id, {
            file: "css/styles.css"
        });
    }
}

因为这些事件是在创建选项卡后立即调用的.每个规则可能必须以!important开头,以防止该规则被页面上的样式表覆盖.

Since these events are called right after the creation of the tabs. each rule might have to be sufficed with !important, to prevent the rules from being overwritten by style sheets on the page.

根据 onCreated 的文档,触发事件时可能未设置url属性,因此请在条件中添加tabUrl &&,以防止可能的错误.

According to the documentation of onCreated, the url property may not be set when the event is fired, so add tabUrl && in the condition, to prevent possible errors.

此外,您的域检查还不够. .indexOf('google.com')也将匹配http://stackoverflow.com/q/x/what-is-google.com?.

Also, your domain check is insufficient. .indexOf('google.com') would also match http://stackoverflow.com/q/x/what-is-google.com?.

这篇关于如何从每个页面的后台页面运行chrome.tabs.insertCSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆