0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Wizard
  • 2,961
  • 2
  • 13
  • 22
  • Try `return { redirectUrl: 'javascript:void 0' }` but it can fail if the site uses a strict CSP. – wOxxOm Jan 02 '23 at 20:49
  • @wOxxOm thanks, but it doesn't work. However, the code I posted doesn't work either, because it creates an infinite loop (request is cancelled, loaded in new tab, then the new request is also cancelled, loaded in another tab etc.) Do you have any idea how to fix that? Basically, I'm trying to replicate Firefox Multi-Account Containers add-on and I have no idea how they are able to create a new tab, without affecting the current one... – Wizard Jan 03 '23 at 07:01

1 Answers1

0

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};
  }
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Thanks. I updated my code to match more closely what I'm doing. The infinite tabs problem is gone. Now, I have to solve the original problem. Say I rapidly click on a bookmark 3 times. With my add-on, 3 new tabs will open, however only the 3rd will load the page. The 2nd click will prevent the page fron loading in 1st tab and the 3rd click will prevent the page fron loading in 2nd tab... Because a second request is being made in 1st and 2nd tab (which will be cancelled my add-on) before the webpage has time to load. – Wizard Jan 03 '23 at 14:12