【问题标题】:sending one time message from background page to devtool page从后台页面向 devtool 页面发送一次消息
【发布时间】:2016-04-27 10:44:00
【问题描述】:

我一直在研究 chrome 扩展,它有时需要传递消息以触发当前网页上的某些事件。

我一直在使用 chrome.runtime.sendMessage 将消息从 devtool 页面发送到后台页面。在后台页面上,我正在使用 chrome.runtime.onMessage.addListener 获取这些消息,并且它正在工作。

但我无法使用此功能将消息从后台页面发送到 devtools 页面! 如何从后台页面向 devtool 页面发送一次消息?

devtool.js

chrome.runtime.onMessage.addListener(function(request){
if(request.name=="xyz")
{
    alert("HI");
}
});

background.js

chrome.runtime.sendMessage({
    name : "xyz"
});

有人可以帮忙吗?

【问题讨论】:

  • 基于此forum,您不能使用chrome.extension.sendMessage() 向在 DevTools 上下文中运行的扩展页面发送消息。从后台页面与 DevTools 通信的最佳方式是使用 chrome.extension.connect 从 DevTools 页面打开一个端口,然后在后台页面中使用 port.postMessage()。
  • @abielita 将该评论作为答案(但请注意,extension 应替换为 runtime

标签: google-chrome-extension google-chrome-devtools


【解决方案1】:

基于此forum,您不能使用chrome.runtime.sendMessage() 向在 DevTools 上下文中运行的扩展页面发送消息。从后台页面与 DevTools 通信的最佳方式是使用 chrome.runtime.connect 从 DevTools 页面打开一个端口,稍后在后台页面中使用 port.postMessage()

【讨论】:

    【解决方案2】:

    如果您有兴趣,我已经创建了一个小型库,它可以为您完成所有工作,并让您可以轻松地在任何扩展部分(特别是在您的情况下,从后台到 devtool)发送消息。

    您可以在这里查看:chrome-ext-messenger

    如果您对如何使用它有任何疑问,请随时与我联系。

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2016-12-01
      • 1970-01-01
      • 2018-06-11
      • 2012-12-30
      • 1970-01-01
      • 2018-07-25
      • 2018-12-25
      • 2022-08-18
      相关资源
      最近更新 更多