1

I am trying to send a message from background.js to content.js. addListener in content.js is not working.

background.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) 
{ 
    console.log(tab.url);
    if(changeInfo.status=="complete"){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            if(tabs.length!=0){
                chrome.tabs.sendMessage(tabs[0].id, {message: "sendurl"}, function(response) {
                    console.log(response.url);
                });
            }
        });
        console.log("load complete");
    }
});

content.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if( request.message === "sendurl" ) {
      var firstHref = $("a[href^='http']").eq(0).attr("href");

      console.log(firstHref);
      sendResponse({url: firstHref});
    }
  }
);

manifest.json

   "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["https://*/","http://*/"],
      "js": ["jquery-2.1.4.js","enc-base64-min.js","hmac-sha256.js","content.js"]

    }
  ],

After some tme, it gives error: TypeError: Cannot read property 'url' of undefined

Harshil Pansare
  • 1,117
  • 1
  • 13
  • 37
  • I generally find it easier to send messages from content scripts to background scripts instead of the other way around. – Teepeemm Sep 29 '15 at 17:29

1 Answers1

1

Your "matches": ["https://*/","http://*/"], only specifies the domain wildcard which means that content scripts are injected for the main page only. The error message you see occurs because sendMessage timeouts after some time as there was no content script to receive the message.

As the match pattern documentation says:

http://*/* Matches any URL that uses the http scheme

The correct code would be "matches": ["https://*/*","http://*/*"],

P.S. Make use of the debugger, it's immensely helpful to catch such errors.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136