[英]Message not passing between content ad background script file
I am trying to send message from background.js
to contentscript file, script.js
. 我正在尝试将消息从background.js
发送到contentscript文件script.js
。 Below is code 下面是代码
script.js 的script.js
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// alert('Message from View:\n'
// + JSON.stringify(msg));
alert(msg);
if (msg.method === 'sendHTML')
{
//process the return code
sendResponse({ data: "Your DOM is here"});
}
});
background.js background.js
chrome.browserAction.onClicked.addListener(function (tab)
{
// var url = tab.url.toLowerCase();
// if(url.indexOf("middlecoin") == -1)
// alert("You are not on MiddleCoin Page");
// else
// chrome.tabs.create({ url: loaderURL + tab.id });
alert("Clicked Call");
chrome.runtime.sendMessage({method: "sendHTML"}, function(response) {
alert(response.data);
});
});
the alert response.data)
is not being called. 警报response.data)
没有被调用。 Where am I doing wrong? 我在哪里做错了?
Let me tell there is NO html file is being in entire extension 我告诉您整个扩展中没有html文件
You need to use chrome.tabs.sendMessage
instead of chrome.runtime.sendMessage
to send a message from background page to content script. 您需要使用chrome.tabs.sendMessage
而不是chrome.runtime.sendMessage
将消息从后台页面发送到内容脚本。 To send a message to the current tab, you can use the tab object passed to your listener for browserAction.onClicked
: 要将消息发送到当前选项卡,您可以使用传递给您的监听器的tab对象进行browserAction.onClicked
:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, {method: "sendHTML"}, function(response) {
alert(response.data);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.