简体   繁体   English

消息未在内容广告背景脚本文件之间传递

[英]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.

相关问题 Chrome 扩展消息在后台和内容脚本之间传递 - Chrome Extension Message Passing between background and content script Chrome扩展程序消息在内容和背景之间传递 - Chrome extension message passing between content and background 在内容脚本和后台页面之间传递消息 - Message passing between content scripts and background page Chrome扩展程序:无法使消息传递在后台脚本和内容脚本之间正常工作 - Chrome extension: can't get message passing to work between background script and content script 是否可以在不使用后台脚本的情况下在多个内容脚本之间传递消息? - Is message passing between multiple content scripts possible without using the background script? 两个内容脚本之间传递的消息(通过后台) - Message passing between two content scripts (through background) 内容和背景之间传递的Chrome扩展程序消息无效 - Chrome extension message passing between content and background not working 在 chrome 扩展中的后台和内容脚本之间传递消息有困难 - Difficulty passing messages between background and content script in chrome extension 在background和content_script之间打开一个用于chrome扩展的消息端口 - Opening a message port between background and content_script for a chrome extension 消息传递:后台脚本到关闭选项卡 - Message passing: Background script to closing tab
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM