【问题标题】:Chrome extension - pass function result from content script to popup.jsChrome 扩展 - 将函数结果从内容脚本传递给 popup.js
【发布时间】:2014-05-30 18:39:16
【问题描述】:

我有 popup.html 扩展,其中包含 popup.js。 我使用 popup.js 使用 chrome.tabs.sendMessage -方法调用位于内容脚本中的函数。 这很好用,但是..

如何将函数的值返回给 popup.js ?我还需要在 popup.js 上设置一个侦听器还是什么?

在我的 popup.js 我有:

chrome.tabs.sendMessage(tab.id, {
 expiryRequest: 'expiry '
}, function (response) {
if (response.refreshResponse === true) {
 console.log('Expiry taken');
} else {
 console.log('Expiry NOT taken');
}
});

这部分效果很好..

在我的内容脚本中,我将某些 div 读入了一个可变的“结果”。 在我使用的内容脚本的功能结束时。

return result;

return true;

这些都不会返回任何返回 tuo popup.js。 为了让我从内容脚本返回到 popup.js,我需要进行哪些更改?

【问题讨论】:

    标签: google-chrome google-chrome-extension content-script


    【解决方案1】:

    您不应该return您的结果,而是将其发回。

    chrome.runtime.onMessage callbacks 有 3 个参数:消息、发送者信息和 sendResponse 回调。

    要返回响应,必须调用 sendResponse

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
      if(message.ping) sendResponse({pong: true});
    });
    

    但是,它还有一个额外的技巧。事件侦听器应立即回复(即同步,在它退出之前)或发出信号表示稍后回复。这是通过返回值完成的:

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
      if(message.ping) {
        chrome.storage.local.get("shouldReply", function(result){
          // This is asynchronous: by now the listener returned
          if(result.shouldReply) sendResponse({pong: true});
        });
      }
      return true; // Indicate that you will eventually call sendResponse
    });    
    

    除非您这样做,否则当侦听器退出并发送未定义的响应时,sendResponse 引用将失效。

    还有一个警告:您应该拨打sendResponse 不超过一次;否则会报错。

    【讨论】:

    • 谢谢你的快速回答,但我还是很困惑。如果我想发回变量“结果”的内容,我该怎么做? sendResponse({result: true});
    • 消息可以是任何东西。您可以简单地返回变量本身:sendResponse(result),或者您可以将其包装在一个对象中:sendResponse({refreshResponse: result})(这将与您的其他代码匹配)
    • 非常感谢@Xan。这是我一直在寻找的答案,尤其是关于返回 true 的最后一部分。我对为什么我的听众提早回来有很多困惑,但是感谢您的回答,现在很清楚:)
    • 哦,这很有趣也很有帮助。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多