简体   繁体   English

Javascript 将消息从 content.js 发送到 background.js

[英]Javascript send message from content.js to background.js

I read some of the chrome docs and got this basic example working.我阅读了一些 chrome 文档并让这个基本示例正常工作。

Now I want to make the request based on an event happening.现在我想根据发生的事件发出请求。 The event is triggered and contentUpdateData() runs, but the chrome.runtime.sendMessage within the function doesn't seem to work.该事件被触发并且 contentUpdateData() 运行,但chrome.runtime.sendMessage中的 chrome.runtime.sendMessage 似乎不起作用。 Any ideas why?任何想法为什么?

/* content.js */ 
var data = []

chrome.runtime.onMessage.addListener(
    function(request, sesnder, sendResponse) {
        if (request.message === 'popupClicked') {
            contentUpdateData();
        }
    }
)

function contentUpdateData() {
    console.log('Code works up to here. Button clicked in popup.html, recieved in content.js. Need to get info from background.js')
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        console.log(response.farewell);
        data = response.data
      });
}
/* background.js basic example from chrome */ 
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting === "hello")
      sendResponse({farewell: "goodbye", data: null});
  }
);

Somehow the background.js did not sync properly after updating the extension.不知何故,更新扩展后 background.js 没有正确同步。 This was the cause for the error.这是错误的原因。

You need to return true from the event listener in backgroundjs.您需要从 backgroundjs 中的事件侦听器return true This saves sendResponse() from garbage collection .这从垃圾收集中保存了sendResponse()

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.greeting === "hello") sendResponse({ farewell: "goodbye", data: null });
  // VERY IMPORTANT
  return true;
});

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

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