1

我知道它已经来过千百次了,但我现在被困住了。我已经阅读了大量答案并研究了 code.google.com 但没有成功。我正在尝试以 chrome 扩展名从background.htmlto发送请求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因为通信正在向后工作并且其他任何东西都可以正常工作。谢谢!

4

1 回答 1

0

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

背景.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"});
        }
});
于 2012-01-14T01:05:03.607 回答