javascript - 卡在消息传递background.html >> contentscript.js(chrome扩展)

标签 javascript google-chrome-extension message-passing

我知道它已经在这里出现了数千次,但我现在被困住了。我读了很多答案并研究了 code.google.com 但没有成功。我正在尝试在 Chrome 扩展程序中从 background.html 发送请求到 contentscript.js。不过,我设法以另一种方式让它工作。

background.html内的代码:

  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
      console.log(response.farewell);
     });
  });

contentscript.js内的代码:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({farewell: "nope"});
});

manifest.json 应该没问题,因为通信正在向后工作,并且其他任何内容都正常工作。谢谢!

最佳答案

你的代码是好的,你的触发器一定有问题。我使用您的代码创建了一个简单的扩展并且它有效。将这两个位添加到您的背景和内容脚本中。然后在任意页面上输入人民币并选择“发送消息”。您应该会收到警报。

背景.html

var menuid = chrome.contextMenus.create({"title":"Send Message", "onclick": SendMessage, "documentUrlPatterns":["http://*/*"]});

function SendMessage() {        
    chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
                console.log(response.farewell);
             });
    });
}

内容脚本

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello") {
            alert('hello');
      sendResponse({farewell: "goodbye"});
        }
    else
        {
            alert('goodbye');
      sendResponse({farewell: "nope"});
        }
});

关于javascript - 卡在消息传递background.html >> contentscript.js(chrome扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858730/

相关文章:

objective-c - 还有哪些其他编程语言具有类似 Smalltalk 的消息传递语法?

在同一个函数中调用 MPI_Barrier 两次可以吗?

javascript - 悬停时播放音频文件

javascript - 使用外部 Node 脚本连接到已在index.js中定义的socket-io

javascript - 具有基本功能的 chrome 扩展内存占用

javascript - background.js 中的 Chrome 扩展 keydown 监听器

ruby - 考虑 Ruby 中的 'self' 关键字的正确方法是什么?

javascript - 动态 checkin 数组

javascript - 如何从无限生成器创建有限长度生成器

javascript - chrome 72 更改了 sourcemap 行为