Hi I have chrome extension with content script that sends message event to background page I would like to modify popup background page on message event. Background page is blank initially
I have 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 extension icon it's still blank. Can you help me please? I can see in console, that message was received.
The popup, while being an extension page, is not a background page. It is only accessible when it is open. Thus, the best way to alter the popup page based on other information would be to initiate the message from the popup itself. I take it you are using the content script to get some sort of info on a page and then changing the popup based on that info. You could either prepare the data and have a onMessage
listener in the content script itself, or you could pass the info to the background page and request it from the popup. An example of the first would be:
Content Script
...
//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 here is it using the background page as an intermediary:
Content Script
// 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 store the info in the background page in a better way than a simple global var. One good way would be to use the storage API
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With