Chrome extension - change the tooltip in a message event

Hi I have a chrome extension with content script that sends a message to the wallpaper I would like to change the popup page in the message event. The original page is empty.

I tried:

chrome.extension.onMessage.addListener(function (request, sender, sendResponse) { console.log('message received'); chrome.extension.getBackgroundPage().document.innerHTML = 'hello world'; } 

But when I click on the extension icon, it still remains blank. could you help me? I can see in the console, this message was received.

+4
source share
1 answer

The popup, being an extension page, is not a background page. It is available only when it is open. Thus, the best way to change a popup page based on other information is to initiate a message from the popup itself. I suppose you use the content script to get some information on the page, and then change the popup based on this information. You can either prepare the data, or listen to onMessage in the content of the script itself, or transfer the information to the background image and request it from the popup window. An example of the first may be:

Script Content

 ... //assume that you already have the info you want stored in 'info' chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ sendResponse(info); }); 

Popup

 chrome.tabs.query({'active': true,'currentWindow':true},function(tab){ chrome.tabs.sendMessage(tab[0].id,"stuff", function(response){ //assuming that info was html markup then you could do document.body.innerhtml = response; //I personally wouldn't do it like this but you get the idea }); }); 

As requested, the man page is used here as an intermediary:

Script Content

 // same assumption that info is already defined as the info you want chrome.runtime.sendMessage({'method':'setInfo','info':info}); 

Background page

 var info; chrome.runtime.onMessage(function(message,sender,sendResponse){ // When we get a message from the content script if(message.method == 'setInfo') info = message.info; // When we get a message from the popup else if(message.method == 'getInfo') sendResponse(info); }); 

Popup

 chrome.runtime.sendMessage({'method':'getInfo'},function(response){ //response is now the info collected by the content script. console.log(response); }); 

Of course, you can save information on the original page better than a simple global var. One good way is to use storage API .

+8
source

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


All Articles