Chrome Extension: Unable to pass message to content.js

ぃ、小莉子 提交于 2019-12-14 02:52:16

问题


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


回答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.



来源:https://stackoverflow.com/questions/32845306/chrome-extension-unable-to-pass-message-to-content-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!