我使用the Google tutorial中的示例,並發現難以將簡單消息從彈出窗口傳遞到內容腳本。來自Chrome擴展程序的消息傳遞示例
您能否提供一些關於如何傳遞簡單消息並在控制檯日誌或警報中查看它的建議?
的manifest.json
{
"manifest_version": 2,
"name": "msg-test",
"description": "message test",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["http://*/*","http://www.site.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}],
"permissions": [
"tabs",
"http://*/*"
]
}
background.js
chrome.runtime.onConnect.addListener(function(port){
port.postMessage({greeting:"hello"});
});
content.js
var port = chrome.runtime.connect({name:"content"});
port.onMessage.addListener(function(message,sender){
if(message.greeting === "hello"){
alert(message.greeting);
}
});
popup.js
window.onload = function() {
document.getElementById('btn2').onclick = function() {
alert("button 2 was clicked");
};
document.getElementById('btn1').onclick = function() {
alert("button 1 was clicked");
};
}
*注:在這個例子中,當頁面相匹配的manifest.json和警報框將顯示內容腳本會火。
@ aclave1您能否介紹一下您的擴展程序的所有文件,我想嘗試一下自己。其他文件(如popup.html)未在developer.chrome.com/extensions/messaging中明確確定 –