Passing message from background.js to popup.js

独自空忆成欢 提交于 2019-11-29 01:53:10

Popup doesn't have tab id so you will get the error.

You can use chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener in that case.

So in background.js

chrome.runtime.sendMessage({
    msg: "something_completed", 
    data: {
        subject: "Loading",
        content: "Just completed!"
    }
});

And in popup.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.msg === "something_completed") {
            //  To do something
            console.log(request.data.subject)
            console.log(request.data.content)
        }
    }
);

I hope it would be helpful to you.

Thanks,

Akshay Singh

To solve this you need to first send a handshake message to background.js and then send the actual data from background.js to popup.js For Example: In my case what i did was

popup.js

chrome.runtime.sendMessage({data:"Handshake"},function(response){
	
			});
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
	str = JSON.stringify(message.data);
});

background.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
//alert(message.data);
	chrome.runtime.sendMessage({data:datax},function(response){
			});
			});

What iam trying to do is that as soon as we click on icon the handshake message is sent to the background.js and when it recieves it we can then send the variable or any data whick we wanted to send on popup.js to render it on popup.html.

Use runtime.sendMessage to send messages to background script, and tabs.sendMessage from background to content script.

Please note that you need to specify tab id:

chrome.tabs.query({ active: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { greeting: 'hello' }, (response) => {
        console.log(response);
    });
});

You can find full example and documentation here: https://developer.chrome.com/extensions/messaging#simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!