简体   繁体   English

Chrome消息传递。 未捕获的错误:连接到分机时出错

[英]Chrome Message passing. Uncaught Error: Error connecting to extension

So I'm very new to Chrome's message passing, and I'm trying to use it to have my background page be alerted when the DOM of a page is modified (using some injected js). 因此,我对Chrome的消息传递非常陌生,并且尝试使用它来在修改页面的DOM(使用注入的js)时提醒我的背景页面。

I'm only trying to have one way communication, but if I open up console on the tab while the extension is running, it tells me "Uncaught Error: Error connecting to extension [my extension id]." 我只是想以一种方式进行通信,但是如果我在扩展程序运行时在选项卡上打开控制台,它会告诉我“未捕获的错误:连接到扩展程序[我的扩展程序ID]时出错”。

For simplicity, I'll say my background page's background.js has these lines of code: 为了简单起见,我会说我的背景页面的background.js包含以下代码行:

chrome.runtime.onMessage.addListener(
  function(){
    if (modified == "true") {
      alert("modified message recieved");
      fourth();
    }
  }
);

And my content script is: 我的内容脚本是:

function subtreeModified(){
  chrome.runtime.sendMessage({modified: "true"});
  alert("modified message sent");
}

document.addEventListener("DOMSubtreeModified", subtreeModified, false);

I've been testing this, and whenever the page DOM is modified, I get a bunch of alerts that say "modified message sent," but none that say "modified message recieved." 我已经对此进行了测试,每当页面DOM被修改时,我都会收到一堆提示“已发送已修改的消息”的警报,但没有一则提示“已接收到已修改的消息”的警报。 Thoughts/tips? 思考/提示吗?

You aren't declaring and using the arguments sent to the receiver's event listener. 您不是在声明和使用发送到接收者的事件侦听器的参数。 Your modified argument is sent as a property on an argument passed to your callback. modified参数将作为传递给回调的参数的属性发送。 That's where you have to get it from when using your code. 那是使用代码时必须从那里获取信息的地方。 Also, I added a console.log() at the start of your callback so you can see if it's getting called: 另外,我在回调的开始处添加了console.log() ,以便查看它是否被调用:

chrome.runtime.onMessage.addListener(function(message) {
    console.log("received message");
    if (message.modified == "true") {
        alert("modified message recieved");
        fourth();
    }
});

Note: it's a little odd to be passing strings for true and false. 注意:传递字符串true和false有点奇怪。 Why not just use booleans? 为什么不只使用布尔值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM