Chrome扩展程序:无法将消息传递给content.js [英] Chrome Extension: Unable to pass message to content.js

查看:166
本文介绍了Chrome扩展程序:无法将消息传递给content.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从background.js向content.js发送消息. content.js中的addListener无法正常工作.

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"]

    }
  ],

经过一段时间后,它给出了错误:TypeError: Cannot read property 'url' of undefined

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

推荐答案

您的"matches": ["https://*/","http://*/"],仅指定域通配符,这意味着仅对主页注入了内容脚本.您看到的错误消息是由于sendMessage一段时间后超时,因为没有内容脚本来接收该消息.

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.

匹配模式文档说:

http://*/*匹配任何使用http方案的URL

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

正确的代码应为"matches": ["https://*/*","http://*/*"],

P.S.利用调试器,对捕获此类错误非常有用.

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

这篇关于Chrome扩展程序:无法将消息传递给content.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆