Canceling request with browser.webRequest.onBeforeRequest also cancels previous pending tab requests

234 Views Asked by At

The following code is used in an add-on to cancel all main-frame requests and re-initiates them in a new tab:

browser.webRequest.onBeforeRequest.addListener(
    filterRequest,
    {urls: ['<all_urls>'], types: ['main_frame']},
    ['blocking']
);

function filterRequest(details) {
    const match = details.url.match(/\/container$/);
    if (!match) {
        return {};
    }
    browser.tabs.create({url: details.url.replace(/\/container$/, '')});
    return {cancel: true}
}

However, if the initial tab had a heavy web-page loading, it stops when the new request is cancelled. I thought that since the request is cancelled, it would be like it was never initiated, so that previous web-page would continue to load. Why is that happening and how can I allow the web-page to finish loading?

1

There are 1 best solutions below

1
On

Save the created tab's id in a global list and check it at the beginning:

const tabIds = new Set();

function filterRequest(details) {
  if (tabIds.has(details.tabId)) {
    tabIds.delete(details.tabId);
  } else {
    browser.tabs.create({url: details.url})
      .then(tab => tabIds.add(tab.id));
    return {cancel: true};
  }
}