简体   繁体   中英

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

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM