(How) Can we use webNavigation to redirect (only navigation web requests)?

I want to redirect visits to a particular URL (in some format, so it’s not one static one, so I need to analyze the URL format) to a different one.

Now, obviously, I see I can do so with webRequest.onBeforeRequest. However, this is fired for loaded assets, images, etc., which I obviously don’t care about and also do not want to accidentally redirect.

So I found the webNavigation API, which seems to be exactly what i want, i.e. only catch the real “navigations” a user does, e.g. when clicking on a link/button, opening a new tab or so, basically everytime the URL in the address bar changes (if I understand it correctly).

But the webNavigation API has no way to redirect or modify anything of the loading request, as it seems. It’s purely static to give you information.

So what is the best way to only redirect some web navigation requests? Can the webRequests be filtered by “onlyNavigation”? Or can one redirect the webNavigation in a clever way?

You could always navigate the tab, I don’t think you can interfere with the navigations directly, as in prevent them fully, unless they’re using the history API in content, so you can control it with a content script.

So basically listen to webNavigation and then use the tab API to navigate the tab away?

Could not webNavigation also trigger when the site is loaded in an iframe or so? To redirect the whole tab would not be preferable, AFAIK.

Thinking about it, as I really only care about top-level navigations, I think actually using only the tab API (and tab.onUpdated) may be actually the best.

I use webRequest with parameter main_frame to listen top- level navigations requests

2 Likes