我是Chrome擴展的新手。我正嘗試在內容腳本和background.html頁面之間進行通信。 background.html向內容腳本發送請求「hello」,內容腳本應迴應「hello background」警報。但這只是沒有發生。我background.html代碼:Chrome擴展程序:內容腳本和background.html之間的通信
function testRequest() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"});
});
}
content.js代碼:
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
alert("hello background");
}
);
popup.html代碼:
<!doctype html>
<html>
<head></head>
<body>
<form>
<input type="button" value="sendMessage" onclick="testRequest()" />
</form>
</body>
</html>
manifest.json的:
{
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
},
"background": {
"page": "background.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"notifications",
"contextMenus"
],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["content.js"]
}
],
"name": "FirstExtension",
"version": "1.0"
}
請幫忙!
非常感謝Rob! :) – Chandeep 2012-08-05 06:33:38
@ user975234順便說一句,Tge [onMessage'上的文檔](http://code.google.com/chrome/extensions/extension.html#event-onMessage)與實際情況不符。有關更多信息,請參閱http://stackoverflow.com/a/11811936。 – 2012-08-05 09:11:20