【问题标题】:Javascript send message from content.js to background.jsJavascript 将消息从 content.js 发送到 background.js
【发布时间】:2022-01-21 04:23:42
【问题描述】:

我阅读了一些 chrome 文档并得到了 this 基本示例的工作。

现在我想根据发生的事件发出请求。该事件被触发并且 contentUpdateData() 运行,但函数中的chrome.runtime.sendMessage 似乎不起作用。任何想法为什么?

/* 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});
  }
);

【问题讨论】:

    标签: javascript


    【解决方案1】:

    不知何故,更新扩展后 background.js 没有正确同步。这就是错误的原因。

    【讨论】:

      【解决方案2】:

      你需要在 backgroundjs 的事件监听器中return true。这从garbage collection 中保存了sendResponse()

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-26
        • 2012-08-29
        • 1970-01-01
        相关资源
        最近更新 更多