'Chrome Extension to Block Stored Links

I am trying to achieve the following: cancel the event (prevent the page from loading) if the link matches one of the links stored in Google storage and open the link in incognito window.

if link exists in Google storage:
  e.preventDefault();

This logic is done in content script by binding the listener on the document object to intercept any links.

document.addEventListener('DOMContentLoaded', () => {
  document.body.addEventListener('click', onClick);
});

However, until I check whether the link exists in Google storage the page finishes loading. I believe this is because chrome.storage.sync.get is asynchronous and the page just finishes loading before e.preventDefault() can be called.

Similar discussion: https://stackoverflow.com/questions/9237044/async-loaded-scripts-with-domcontentloaded-or-load-event-handlers-not-being-call[][1].

The functionality I need: https://stackoverflow.com/questions/38619308/how-to-block-a-tab-from-opening-a-page-on-webnavigation-onbeforenavigate-event[][2]

Problem with the accepted answer is that the page is partially loaded. I do not want to load the page at all.

How can I get the list of links ready from Google storage without asynchronous calls inside onClick? Or how can I achieve the desired functionality differently?



Solution 1:[1]

I used chrome.declarativeNetRequest API to redirect user listed domain names to https://google.com/gen_204, and onRuleMatchedDebug event to get the original URL and open it in incognito window.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 niyazisuleymanov