Chrome扩展程序:从background.js到content.js的消息 [英] Chrome extension: message from background.js to 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.runtime.sendMessage
向所有打开扩展页面发送消息(即背景,弹出窗口,等等) -
chrome .tabs.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.
chrome.runtime.sendMessage
sends a message to all open extension pages (i.e. background, popup, etc.)chrome.tabs.sendMessage
sends a message to all content scripts from the extension in a given tab
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屋!