2012-01-13 158 views
1

我知道它已经在这里像千次,但我现在卡住了。我读了很多答案,并研究了code.google.com,但没有成功。我正试图发送一个从background.htmlcontentscript.js的Chrome扩展请求。尽管我设法让它以另一种方式工作。卡住消息传递background.html >> contentscript.js(扩展名为Chrome)

代码中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应该罚款和其他任何工作正常。谢谢!

+0

是contentscript收到的消息? – 2012-01-13 23:44:02

+0

不,即使我添加'alert(“嘿”);'在函数内部(request,sender,sendResponse){}'没有任何反应。 – 2012-01-13 23:53:06

回答

0

你的代码很好,你的触发器肯定有问题。我使用你的代码创建了一个简单的扩展,它工作。将这两位添加到您的背景和内容。然后在任何页面上选择“发送消息”。你应该收到一个提醒。

Background.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); 
      }); 
    }); 
} 

contentscript

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

谢谢,这个工程。但仍然不知道为什么其他方式没有。我使用了动作浏览器的onclicked事件,它也能正常工作。 – 2012-01-16 23:22:45

相关问题