Chrome.runtime.onMessage.addListener not registering within the created tab

The following script is injected from my background.js when I create a new tab (the new tab loads the site i.e. google.com).

$(function(){
  //this fires when tab is created and script injected
  chrome.runtime.sendMessage({title: window.document.title}, function(){});
  //this fires when clicking on element in created tab
  document.getElementById("Username").addEventListener("click", function(){
    chrome.runtime.sendMessage({someMessageFromLiveSite: 'Clicked in live site!'});
  });

  chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
    //this never fires
    chrome.runtime.sendMessage({title: 'This is the created tab responding to a msg'}, function(){});
    //code continues...

      

As noted above, chrome.runtime.sendMessage

it seems to work fine, as does the Java formatted event listener, but the listener chrome.runtime.onMessage

doesn't seem to be added / responded to messages sent from other parts of the extension (background or other generated pages).

0


source to share


1 answer


Thanks to Xan's answer here , I figured out that I was trying to broadcast a message to all of my created tabs from the background using chrome.runtime.sendMessage

, but as explained, this is not broadcast, so it is required chrome.tabs.sendMessage(TAB_ID....

for the listener to listen to my content tab.



While the title is technically inaccurate for the problem I was facing, it seemed like the correct symptom to me, so this answer may still help others.

0


source







All Articles