About sending messages between bg.html, popup.html and contentscript.js

In my extension, when a button named mybuttonl in popup.html clicked, it sends a "getvar" message to contentscript.js , which in turn sends a "I want var1" message to background.html to get an object named var1 . (The button with the name mybutton2 configured in the same way, except that when you click on it, the var2 object appears).

How to implement this?

What else, I got a little confused about the chrome.extension.onRequest.addListener and chrome.extension.sendRequest . Can someone explain?

+4
source share
1 answer

onRequest.addListener and sendRequest are part of Chrome’s advanced messaging. Here is http://developer.chrome.com/extensions/messaging.html

Basically, you are listening to a request using "onRequest.addListener", which someone sent from the start of "sendRequest".

In your case, you put onRequest.addListener in your script content to listen for requests coming from a popup (using sendRequest ). And from your script content, you can return a response to your popup to deal with what is happening. In your popup, you have direct access to the background page using chrome.extension.getBackgroundPage () .

If you want your script content to also link to your background page (which is not required as your material becomes more complex), you can add "onRequest.addListener" to your background page, which only listens for requests based on the contents of the script. For this, Message Passing perfectly explains this. "sender.tab", if true, is the contents of the script.

The example below (untested) shows what I mean by message passing. Remember, try to keep things simple, not complicated.

Example

Popup.html

 chrome.tabs.getSelected(null, function(tab) { chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) { console.log(response.data); }); }); 

ContentScript.js

 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method == "fromPopup") { // Send JSON data back to Popup. sendResponse({data: "from Content Script to Popup"}); // Send JSON data to background page. chrome.extension.sendRequest({method: "fromContentScript"}, function(response) { console.log(response.data); }); } else { sendResponse({}); // snub them. } }); 

BackgroundPage.html

 chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { // From content script. if (sender.tab) { if (request.method == "fromContentScript") sendResponse({data: "Response from Background Page"}); else sendResponse({}); // snub them. } }); 
+16
source

Source: https://habr.com/ru/post/1306536/


All Articles