injected in content_scripts doesn't get applied to document element in background.js

问题描述 投票:0回答:2

我有一个脚本设置为“run_at”:“document_idle”,它会在标题中注入一个标记。但是,尝试将其中定义的类应用于稍后的元素不会导致元素的任何更改。

manifest.json的:

{
    "manifest_version": 2,
    "name": "Test",
    "description": "make color",
    "version": "1.0",
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "content_scripts": [
    {
        "matches": ["*://*/*"],
        "js": ["pageload.js"],
        "run_at": "document_idle"
    }],
    "browser_action": {},
    "permissions": ["*://*/*","activeTab","tabs"]
}

pageload.js:

'use strict';

// onload, add our class "highlight"
var css = "\n\t.highlight { background-color: yellow; }\n",
    rstyle = document.createElement('style');

// Append style element to head
document.head.appendChild(rstyle);

//rstyle.type = "text/css";
rstyle.appendChild(document.createTextNode(css));

background.js(按下按钮运行):

'use strict';

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {

    // toggle putting the class on the body
    document.body.classList.toggle('highlight');

});

页面加载时,我会看到标题中的元素。当我单击按钮时,我看到“class ='highlight'”出现在独立(背景页面)dev元素中,而不是浏览器dev元素。谁知道我错过了什么?谢谢!

google-chrome-extension google-chrome-devtools
2个回答
0
投票

后台脚本在自己的DOM中执行。要在活动选项卡中修改文档,您需要在清单的权限中使用“activeTab”权限,并以下列方式执行代码

chrome.tabs.query({active: true, currentWindow: true}, 
function(tabs) {
    chrome.tabs.executeScript(
        tabs[0].id,
        {code: "document.body.classList.toggle('highlight');"});
});

0
投票

这最终对我有用 - 在后台和内容源之间使用消息传递:

'use strict';

// onload, add our class "highlight"
var css = "\n\t.highlight { background-color:yellow; }\n",
    rstyle = document.createElement('style');

// Append style element to head
document.head.appendChild(rstyle);

rstyle.type = "text/css";
rstyle.appendChild(document.createTextNode(css));

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if( request.message === "toggle_highlight" ) {
        document.body.classList.toggle('highlight');
    }
  }
);

'use strict';

chrome.browserAction.onClicked.addListener(function(tab) {
  // Send a message to the active tab
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "toggle_highlight"});
  });
});