Chrome扩展程序:从background.js到content.js的消息 [英] Chrome extension: message from background.js to content.js

查看:2179
本文介绍了Chrome扩展程序:从background.js到content.js的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



背景

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

内容

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

background.js 从单击事件中发生的 popup.js 接收特定消息。因此,用户点击弹出窗口中的按钮,然后将消息发送到后台,然后发送到内容。



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



请帮助我

解决方案

在Chrome API中有2 sendMessage 函数





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



<在这两种情况下,事件都是 chrome.runtime.onMessage 消息文档了解更多详情。


I am trying to send a message from background.js to content.js using the following code:

Background

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

Content

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

The background message is sent when background.js receives a specific message from popup.js which occurs on a click event. So the user clicks a button in the popup and a message is sent to background and then to content.

I have a feeling my problem is something to do with the fact that when the button is clicked in the popup (which is a separate tab), the content script does not receive it because it is not the current active tab.

Please help me out.

解决方案

There are 2 sendMessage functions in Chrome API.

So, to send a message TO a content script, you need to use chrome.tabs. To send a message FROM a content script (or within the extension pages), you need to use chrome.runtime.

The event is chrome.runtime.onMessage in both cases.

See Messaging docs for more details.

这篇关于Chrome扩展程序:从background.js到content.js的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆