将更新从内容脚本发送到弹出窗口的正确方法

时间:2015-05-20 11:24:38

标签: google-chrome-extension

我的扩展程序包含content_scriptbackground_pagepage_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更新的最佳做法是什么?

0 个答案:

没有答案
相关问题