简体   繁体   English

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

[英]Websockets - pass data outside of onmessage()

My WebExtension connects to a WebSockets server to retrieve data. 我的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"]
)

Whenever a request is completed, function foo() is called which opens a WebSocket to ws://localhost:9876 , sends a string, then receives data . 每当请求完成时,都会调用函数foo() ,该函数将打开一个WebSocket到ws://localhost:9876 ,发送一个字符串,然后接收data The data determines whether or not the request will be blocked. 数据确定是否将阻止该请求。

After reading through the answers here , I'm still confused. 看完这里的答案后 ,我仍然很困惑。 I'm not sure how to implement the callback while within function foo() . 我不确定如何在函数foo()实现回调。

Similar question but the answer is not what I'm looking for. 类似的问题,但答案不是我想要的。

You can use promises for this exact use-case, something as follows should work: 您可以在这个确切的用例中使用promise,以下方法应该可以工作:

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"]
)

More info can be found here 更多信息可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM