我目前正在尝试编写Chrome扩展程序,通知我目标网页上的DOM更改。
如果元素发生更改,内容脚本将使用长期连接将消息发送到后台页面。 Console.log
显示消息的内容,一切似乎都很好。
但是,如果我从后台页面向弹出窗口console.log
发送相同的消息,则显示undefined
。我使用了chrome.runtime.sendMessage
和chrome.extension.sendRequest
但结果是一样的。使用chrome.runtime.connect
将背景连接到弹出窗口会引发Attempting to use a disconnected port object
,尽管它可以将消息从内容脚本发送到后台页面。
我想将content_script中的通知发送到后台弹出窗口。虽然我不确定我是否需要首先将它发送到后台,或者将它直接发送到弹出窗口是否更好。
我还不熟悉Chrome扩展程序并尝试弄清Google's site中的示例如何工作。
我的代码:
的manifest.json
{
"name": "Chrome Extension \\o.o/",
"description": "doing stuff",
"version": "1.0",
"manifest_version": 2,
"permissions":
[
"tabs",
"http://*/*",
"background"
],
"background":
{
"scripts": ["background.js"]
},
"content_scripts":
[{
"matches": [" /* my website */ "],
"js": ["content_script.js"]
}],
"browser_action":
{
"default_popup": "popup.html"
}
}
content_script.js
var audio = document.getElementById("audioSource");
// Open up a long-lived connection to background page
var port = chrome.runtime.connect({name:"stuffChanged"});
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log("stuff happened, audio source changed to " + audio.src);
// notify background page
port.postMessage({notification: audio.src});
})
});
observer.observe(document.getElementById("audioSource"), {attributes: true});
background.js
var toPopup = chrome.runtime.connect({name:"update"});
chrome.runtime.onConnect.addListener(function(port){
if(port.name == "stuffChanged"){
port.onMessage.addListener(function(msg){
var notif = msg.notification;
// message from content_script, works
console.log(notif);
// send to pop up
// returns undefined
chrome.runtime.sendMessage({update: notif});
// disconnected port object
toPopup.postMessage({notification: notif});
});
}
});
popup.js
// returns undefined
chrome.extension.onMessage.addListener(function(msg){
console.log(msg.udpate);
});
// doesn't work at all
chrome.runtime.onConnect.addListener(function(toPopup){
toPopup.onMessage.addListener(function(msg){
console.log(toPopup.notification);
});
});
有人可以帮忙吗?