Background.js Doesn't Find Content Injected with Content Script

爷,独闯天下 提交于 2020-01-11 14:18:28

问题


My Chrome extension has a Content-Script that injects a custom DIV into the current page. This part works.

But then, the extension also has a right-click Context Menu, which when clicked, should modify this injected DIV in some way (let's say, add some text into that DIV). The issue is that the injected content isn't found. The right-click menu handler is in Background.js, and this file doesn't know anything about the content.

manifest.js

"content_scripts": [
    {
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "css": ["contentstyle.css"],
    "js": ["jquery-1.11.2.min.js", "contentscript.js"],

"background": {
    "persistent": true,
    "scripts": ["background.js"]  
},     

contentscript.js

// Add Custom DIV - works OK
var div = document.createElement( 'div' );
div.id = 'infoDiv';
document.body.appendChild( div );
document.getElementById('infoDiv').innerHTML = 'TEST';

background.js

// Add menu - gets added, but can't see Injected Content from here
chrome.contextMenus.create({
    "title": "My Right-Click Menu",
    "contexts": ["image"],
    "onclick" : changeDiv
  });

function changeDiv(e)
{
    var divHTML = document.getElementById('infoDiv').innerHTML;
    alert('Current HTML in DIV: ' + divHTML);
}

I'm unable to get the divHTML from the Background script, there is some kind of error and no alert box. Can there be communication between the Background and Content? I'm forced to implement menus in the Background script, right?


回答1:


Wrong document in

var divHTML = document.getElementById('infoDiv').innerHTML;

Please read the Architecture Overview first. Your background script is executed in a separate HTML document, and as such won't "see" the page in the tab.

You'll need to pass the value to the content script to do something with a visible page. You'll probably need Messaging.



来源:https://stackoverflow.com/questions/29931183/background-js-doesnt-find-content-injected-with-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!