Harshil Pansare
Harshil Pansare

Reputation: 1147

Chrome Extension: Unable to pass message to content.js

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

Upvotes: 1

Views: 133

Answers (1)

woxxom
woxxom

Reputation: 73806

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.

Upvotes: 1

Related Questions