【问题标题】:send data from background.js to popup.html将数据从 background.js 发送到 popup.html
【发布时间】:2014-09-01 15:40:38
【问题描述】:

在我的background.js 中,当加载过程中匹配 URL 时,它加载了 ajax。例如,它是 google.com,它会触发一个 ajax 并接收一些数据。但是如何将这些数据发送到我的 popup.html?

我试过chrome.runtime.sendMessage,但我不明白。参数发送到哪个文件?

我很困惑。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    当您通过chrome.runtime.sendMessage 发送数据时,您将能够通过收听onMessage 事件在弹出窗口中获取数据。

    当你像这样从 background.js 发送消息时,

    chrome.runtime.sendMessage({msg: 'hello there'});
    

    可以在popup.html加载的js文件中获取:

    chrome.extension.onMessage.addListener(function(message, messageSender, sendResponse) {
        // message is the message you sent, probably an object
        // messageSender is an object that contains info about the context that sent the message
        // sendResponse is a function to run when you have a response
    });
    

    herehere

    【讨论】:

    • 嘿,谢谢你的回答。我试过了,但没有用。我把这个 chrome.runtime.sendMessage({greeting: "hello"}) 放到我的 bg.js 和这个 chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.greeting == "hello ") 警报('是'); });进入popup.html(我实际上使用了include)但是当我点击弹出窗口时什么也没发生。
    • 这可能是因为当您从后台发送消息时,您的弹出窗口已关闭,因此没有人收到消息。当您打开弹出窗口时,它正在侦听,但消息已发送。但你可以用相反的方式做到这一点。弹出和后台脚本都可以以相同的方式发送和收听消息。当您打开弹窗时,向后台发送消息,并在后台收听此消息并在收到消息时发送消息。这次你的弹出窗口应该会收到消息。
    • 因为当用户看到弹出窗口时我不希望有任何延迟。如果我做相反的方式,它会延迟吗?因为在我的 bg.js 中,我做 ajax 调用。
    【解决方案2】:

    您可以编辑您的问题以包含您的 manifest.json 吗?这在提出建议时通常非常有用。

    假设您的 popup.html 是内容脚本的一部分,您需要使用 chrome.tabs.sendMessage 将消息从后台页面发送到内容脚本。

    还可以考虑使用 chromeps 在整个扩展程序中进行简单的 pubsub 样式消息传播,而不必担心何时使用 chrome.runtimechrome.tabs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2021-11-24
      • 2013-11-29
      • 2015-04-19
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      相关资源
      最近更新 更多