0

My WebExtension connects to a WebSockets server to retrieve data.

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. 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().

Similar question but the answer is not what I'm looking for.

Community
  • 1
  • 1

1 Answers1

2

You can use promises for this exact use-case, something as follows should work:

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

Dieterg
  • 16,118
  • 3
  • 30
  • 49