user6753818
user6753818

Reputation:

Chrome Extension - onMessage in popup not receiving message from injected script

I'm very new to Chrome extension development, and I want to do something super simple but I'm not sure why it's not working. In essence, I want to:

The permissions in my manifest are "activeTab", "storage", "tabs".

Here is the code I'm trying to use for testing purposes

popup.js

chrome.tabs.executeScript(null, {file: "injected.js"});                          

chrome.runtime.onMessage.addListener(                                            
    function(request, sender, sendResponse){                                  
            console.log("message received!");                                
});    

injected.js

var url = "";                                                                    

// get the url of the current tab                                                
chrome.tabs.query({currentWindow: true, active: true},                           
        function(tabs) {                                                         
                url = tabs[0].url;                                               
                console.log("running");                                          
});                                                                              

chrome.runtime.sendMessage({"url": url});    

The problem is that "message received!" never prints to the console when I use the debugger, however "running" will print just fine. I have looked at questions that seem to have a similar problem:

None of the accepted answers seem to work for me. I've tried adding return true; to the onMessage event listener and it didn't seem to work. I'm also not getting any errors on the console in the debugger (from clicking "Inspect Popup"). I feel like I'm missing something trivial, but I don't know enough to make a guess at what it is. Is there a reason why onMessage isn't receiving anything?

Upvotes: 2

Views: 1212

Answers (1)

woxxom
woxxom

Reputation: 73506

The documentation lists several chrome API allowed in a content script, not chrome.tabs.

Solution: use chrome.tabs in a privileged page like the popup.

Like all Chrome API with a callback function chrome.tabs.query is asynchronous and invokes the callback after current function/context has been executed. So the next statement will only see the old url (empty string).

Solution: process the received data right in the callback.

So in your scenario there's no need for a content script at all, along with "tabs" permission as you can see in "activeTab" documentation: it automatically sets temporary permission after a user gesture such as clicking an extension toolbar popup.

Upvotes: 1

Related Questions