微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Chrome 扩展消息无法通过

如何解决Chrome 扩展消息无法通过

ma​​nifest.json:

{
  "manifest_version": 2,"name": "chrome-extension-bar","description": "Chrome Extension Bar","version": "1.0","browser_action": {
    "default_title": "Chrome Extension Bar","default_icon": "icon.png","default_popup": "popup.html"
  },"background": {
    "service_worker": "background.js"
  },"permissions": [
    "<all_urls>","tabs"
  ],"content_security_policy": "script-src 'self' https://ajax.googleapis.com/ https://maxcdn.bootstrapcdn.com ; object-src 'self'"
}

background.js:

console.log("In background.js")
chrome.runtime.onMessage.addListener (
    function (request,sender,sendResponse) {
        console.log("In listener");
        // to send back your response  to the current tab
        chrome.tabs.query({active: true,currentwindow: true},function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id,{fileData: response},function(response) {
                sendResponse({farewell: "goodbye"});
            });
        });

        return true;
    }
);

content_script.js:

var current_title_bar = document.getElementById("global-nav");
console.log("Title bar:" + current_title_bar);
current_title_bar.appendChild(extension_bar); // <= GODD,getting here

document.getElementById("idStartButton").addEventListener('click',function () {
    console.log('Sending start button message: ' + document.getElementById("idNumSecondsPerPage").value);
    chrome.runtime.sendMessage({numSecondsPerPage : document.getElementById("idNumSecondsPerPage").value},function(response) {
        console.log('Got response: ' + response.farewell);
      });
});

document.getElementById("idStopButton").addEventListener('click',function () {
    console.log('Sending stop button message: ' + document.getElementById("idNumPages").value);
    chrome.runtime.sendMessage({numPages : document.getElementById("idNumPages").value},function(response) {
        console.log('Got response: ' + response.farewell);
      });
});

消息似乎正在发送,但我没有从接收者那里得到任何东西。

控制台登录表单被注入的页面

Entering content_script.js
content_script.js:156 Title bar:[object HTMLElement]
content_script:161 Sending start button message: 67
content_script:168 Sending stop button message: 76

为什么 background.js 发送的消息没有被 content_script.js 接收?他们甚至被发送了吗?

解决方法

如果您想从 background.js 脚本向 content_script.js 发送消息,那么您需要在内容脚本上设置一个 onMessage 侦听器。

在这种情况下,您可能会做的是,在后台脚本上接收到事件后,只需调用回调函数,而不是发送带有回调函数的新事件,而不是执行,调用第一个事件的回调函数。

而不是这样做:

console.log("In listener");
// to send back your response  to the current tab
chrome.tabs.query({active: true,currentWindow: true},function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id,{fileData: response},function(response) {
        sendResponse({farewell: "goodbye"});
    });
});

就这样做

console.log("In listener");
// send back your response
sendResponse({farewell: "goodbye"});
        

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。