I am making my first Firefox extension using the WebExtension API and cannot find a way to redirect a website to an HTML file that is in the extension\'s directory.
I ha
You are changing the URL of the page to one that is relative to the current domain. The page in your extension is not in the reddit.com domain. If you want to the URL to be from a different domain, you have to specify the domain. In this case, you need to use runtime.getURL() to get the fully qualified URL:
Firefox or Chrome:
window.location = chrome.runtime.getURL("interface/redirect.html");
or (Firefox only):
window.location = browser.runtime.getURL("interface/redirect.html");
You should also add:
"run_at": "document_start"
to your manifest.json content_scripts
entry. Doing so will prevent the page from being displayed, even for a brief time. In other words, by using document_start
, your content script will run prior to the redit.com page being rendered.
The approach you are taking, using a content script, is a reasonable one to use when you want to redirect a single, or a few, predefined domains. It will result in the least broad permissions being reported to the user (i.e. only the domains in your matches
).
However, for redirecting a dynamic list of domains, it is not sufficient. In that case, you should use a webNavigation.onBeforeNavigate listener to perform the redirection of the navigation. You could also use a webRequest listener to redirect all traffic to one or more domains. Using webRequest
can be used to block all requests to the domain, but is more resource intensive than just blocking navigation using webNavigation.onBeforeNavigate
(including iframes, if you choose). Which method you use will depend on what you are desiring to do.
You could also use a tabs.onUpdated
listener to perform the redirection, but that event with the new URL fires after the webNavigation.onBeforeNavigate
and the entire webRequest
sequence. In other words, using a tabs.onUpdated
listener will still allow the request to the domain you are redirecting to have been made, the DOM for the page to have been created and potentially shown (briefly) to the user.