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:
- Run a popup.js script which programmatically injects a script
- Have the injected script get some data from the active tab
- use chrome.runtime.sendMessage to send the data back to popup.js
- Do something when the data is received in popup.js (for example, displaying the active tab's URL in the extension popup)
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:
- Chrome Extension Message passing: response not sent
- Chrome extension : error when sending message back from injected script to background script
- Message Passing Example From Chrome Extensions
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?