Websockets - 在onmessage()之外传递数据

时间:2017-05-12 14:15:39

标签: javascript websocket firefox-webextensions

我的WebExtension连接到WebSockets服务器以检索数据。

function foo(responseDetails){
    var ws = new WebSocket("ws://localhost:9876/");

    ws.onopen = function(event){
        // send some data to the server
        ws.send("some data");
    }

    ws.onmessage = function(event){
        // receive some data from the server
        data = event.data;
    }

    // how to access the data from here?
    if(data == 0)
        return {cancel:true}
    else
        return {cancel:false}
}

browser.webRequest.onBeforeRequest.addListener(
        foo, 
        {urls:["*//*/*"]},
        ["blocking"]
)

每当请求完成时,调用函数foo(),将WebSocket打开到ws://localhost:9876,发送一个字符串,然后接收data。数据确定是否阻止请求。

阅读the answers here后,我仍感到困惑。我不确定如何在函数foo()内实现回调。

Similar question但答案不是我正在寻找的。

1 个答案:

答案 0 :(得分:1)

你可以对这个确切的用例使用promises,如下所示:

function foo(responseDetails) {
  return new Promise(function(resolve) {
    var ws = new WebSocket("ws://localhost:9876/");

    ws.onopen = function(event) {
      // send some data to the server
      ws.send("some data");
    }

    ws.onmessage = function(event) {
      // receive some data from the server
      var data = event.data;
      if (data == 0) {
        resolve({
          cancel: true
        });
      } else {
        resolve({
          cancel: false
        })
      }
    }
  });
}

browser.webRequest.onBeforeRequest.addListener(
  foo, {
    urls: ["*//*/*"]
  }, ["blocking"]
)

可以找到更多信息here