如何在后台脚本和页面(弹出)脚本之间进行通信?

时间:2016-10-07 14:07:59

标签: javascript firefox-webextensions

如何从页面(弹出)脚本控制后台脚本中的变量?
为了每10秒获取一次资源,我在下面的代码中使用了setTimeout循环 但是当我取消选中弹出页面(browser_action)中的复选框时,下面的代码不会停止循环。

我预计当我(选中或取消选中)弹出窗口中的复选框时,page_script会向后台脚本发送消息,如果后台收到stop_loop消息,则后台脚本会将settimeout_loop_controller更改为false以停止settimeout循环。

但是当我点击复选框时,这些代码没有反应。

如何在两个脚本之间进行通信?

let settimeout_loop_controller = true;

function fetching() {
    if (settimeout_loop_controller) { 
    // if 'settimeout_loop_controller become false, the loop will stop.
        fetch("http://url.com/example").then((getval) => { do_something })...  ;
        setTimeout(fetching, 10000);
    } else {
        return;
    }
}

fetching();

chrome.runtime.onMessage.addListener((message) => {
    if message.type === "stop_loop" {
        settimeout_loop_controller = false;
    }
    else if (message.type === "start_loop") {
        settimeout_loop_controller = true;
        fetching();
    }
});

弹出脚本:

let checkbox = document.getElementById("checkbox");

checkbox.onchange((e) => {
    if (checkbox.checked) {
        chrome.runtime.sendMessage({"type": "start_loop"});
    }
    else {
        chrome.runtime.sendMessage({"type": "stop_loop"});
    }
});

1 个答案:

答案 0 :(得分:2)

页面脚本中不存在chrome.runtime.sendMessage API,但可以在内容脚本中访问它。典型用法是页面脚本使用window.postMessage({"type": "stop_loop"},"*")将消息发布到内容脚本,然后在内容脚本中转发消息。 /> 对于Firefox 49及更高版本,您可以Sharing objects with page scripts。例如,您可以先在内容脚本中定义函数notify()exportFunction(notify, window, {defineAs:'notify'});。页面脚本将能够调用window对象中的公开函数。

  

window.notify(“来自页面脚本的消息!”);