我的扩展程序包含content_script
,background_page
和page_action
以及弹出窗口。
因此,弹出窗口有几个控件,当用户按下控件时,弹出窗口应该发送一个命令来开始工作。内容脚本开始工作,应该向弹出窗口发送更新。
问题是我不确定我是否正确实施了更新部分。
内容脚本:
function notifyProgress(thing) {
console.log('Notify progress');
chrome.runtime.sendMessage({req: 'Progress', thing: thing});
}
背景页面:
var channel;
chrome.runtime.onConnect.addListener(function (port) {
if (port.name == 'service-channel') {
channel = port;
port.onMessage.addListener(function (msg) {
console.log('Background received event', msg);
...
});
}
});
...
chrome.runtime.onMessage.addListener(function (msg, sender, callback) {
console.log('On message in background', msg);
if (msg.req == '...') {
...
} else if (msg.req == 'Progress') {
console.log('Got Progress for ' + sender.tab.id);
channel.postMessage(msg);
}
});
弹出窗口:
var channel = chrome.extension.connect({name: 'service-channel'});
channel.onMessage.addListener(function (message) {
if (message.req == '...') {
...
} else if (message.req == 'Progress') {
updateListener(message.req, {thing: message.thing}); // updates UI
} else
console.log('Ignoring', message);
});
此外,我担心发送Progress
个事件的多个工作内容脚本。
有更简单或更好的方法吗?
修改
从内容脚本实施Popup更新的最佳做法是什么?