Chrome OnMessage Extension

I'm new to Chrome extensions, and of course I'm stuck at every turn, but it's especially difficult. This may be a stupid mistake, but here is what I am trying to do:

Send a simple message from the contents of the script to the source page and treat it as a variable. So I have this in my content script:

$(document).ready(function() { var d = document.domain; chrome.extension.sendMessage({dom: d}); }); 

And in my background the script is this:

 chrome.extension.onMessage.addListener(function(request) { alert(request.dom); }); 

So the warning is working fine. But it "goes" to the page on which I pounce, and not the HTML extension, which means that instead of appearing when I click on my extension button, it will appear because it was encoded into the script content when the page loads.

Please any help would be appreciated.

+6
source share
1 answer

My demo extension is as follows

Files and Roles

a) manifest.json (Documentation)

b) myscript.js (Script Content See Documentation )

c) background.js (Background HTML file See Documentation )

d) popup.html (browser popup See Documentation )

e) popup.js (Modified value receptor from the manual page)

manifest.json

Register all files in the manifest (Viz background, popup, content scripts) with permissions

 { "name":"Communication Demo", "description":"This demonstrates modes of communication", "manifest_version":2, "version":"1", "permissions":["<all_urls>"], "background":{ "scripts":["background.js"] }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["myscript.js"] } ], "browser_action":{ "default_icon":"screen.png", "default_popup":"popup.html" } } 

myscript.js

Used by sendMessage () API to communicate with the background page

 var d = document.domain; chrome.extension.sendMessage({ dom: d }); 

background.js

Content listeners for content and popup.js have been added using onMessage () and onConnect () Listeners

 var modifiedDom; chrome.extension.onMessage.addListener(function (request) { modifiedDom = request.dom + "Trivial Info Appending"; }); chrome.extension.onConnect.addListener(function (port) { port.onMessage.addListener(function (message) { if (message == "Request Modified Value") { port.postMessage(modifiedDom); } }); }); 

popup.html

Example browser action HTML page registering popup.js to avoid inline scripts

 <!doctype html> <html> <head> <script src="popup.js"></script> </head> <body></body> </html> 

popup.js

Used by Port \ Long Lived Connection to link to the background page for results

 var port = chrome.extension.connect({ name: "Sample Communication" }); port.postMessage("Request Modified Value"); port.onMessage.addListener(function (msg) { console.log("Modified Value recieved is " + msg); }); 

Hope this helps, let me know if you need more info.

+15
source

All Articles