Rx.js, handling Chrome Extension webrequest API callback functions
Asked Answered
S

0

1

I'm trying to use Rx.js to handle the flow of Chrome extension webrequest API.

Each webrequest addListener() call takes a mandatory callback function as the first parameter. This sends request objects to the function. However, the callback can return a webRequest.BlockingResponse that determines the further life cycle of the request.

I'm struggling to handle the blocking response as part of the observable.

This code works well for examining all image requests, for example

onBeforeRequestHandler = function() {

        var filteredURLs = ["http://*/*", "https://*/*"]; 
        var resourceTypes = ["image"]; 
        var filter = { urls: filteredURLs, types: resourceTypes };
        var options = ["blocking"];

        return Rx.Observable.create(observer => {
            var listener = chrome.webRequest.onBeforeRequest.addListener(
                function requestHandler(obj) {
                    observer.next(obj);
                },
                filter, options);
            return unsubscribe => {
                chrome.webRequest.onBeforeRequest.removeListener(listener);
            };
        });

};

I can then use all the Rx.js operators to manipulate the requests by doing this:

var source = onBeforeRequestHandler();
source.subscribe();

etc.

However, if during the course of working the images, I wish to cancel the request, I somehow need to return a blocking response object, like this {cancel:true} to the observable that is wrapping the chrome.webRequest.onBeforeRequest.addListener callback function.

At the moment I have no clue how to do this.

Any help much appreciated.

Stoffel answered 22/2, 2018 at 13:13 Comment(1)
As a quick addendum, I was thinking that local storage might give me a way out of this. That depends on the call to observer.next though. Does the Javascript thread move on from observer.next as soon as it has entered the observable chain or once it has exited via subscribe? If the latter, then you could write to local storage during the sequence process and then retrieve it in the function above.Stoffel

© 2022 - 2024 — McMap. All rights reserved.