【问题标题】:Chrome extension: message from background.js to content.jsChrome 扩展:从 background.js 到 content.js 的消息
【发布时间】:2018-06-18 16:28:49
【问题描述】:

我正在尝试使用以下代码从background.jscontent.js 发送消息:

背景

chrome.runtime.sendMessage({'method': 'test'});

内容

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.method == 'test')
    console.log('Got message');
});

background.js 收到来自popup.js 的特定消息时发送后台消息,该消息发生在点击事件上。所以用户点击弹出窗口中的一个按钮,一条消息被发送到后台,然后发送到内容。

我感觉我的问题与以下事实有关:当在弹出窗口(这是一个单独的选项卡)中单击按钮时,内容脚本没有收到它,因为它不是当前的活动选项卡。

请帮帮我。

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    Chrome API 中有 2 个sendMessage 函数。

    因此,要向内容脚本发送消息,您需要使用chrome.tabs。要从内容脚本(或在扩展页面内)发送消息,您需要使用 chrome.runtime

    在这两种情况下,事件都是chrome.runtime.onMessage

    更多详情请见Messaging docs

    【讨论】:

    • 有道理!感谢您的帮助。
    • 这也帮助了我here 当我认为我的问题来自另一方时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多