Chrome extension default html or 404 (for single-page app routing)

977 views Asked by At

Our Chrome extension browser action opens a new tab:

chrome.tabs.create({
  url: chrome.extension.getURL('/html/main.html?route=/home')
})

main.html is a single-page app entry that uses the HTML5 history API (history.pushState) to change /html/main.html?route=/home to /home. This works, and navigation within the app works.

The only problem is that if the user refreshes the page /home will 404.

This webpage is not found ERR_FILE_NOT_FOUND

Is there a way to make a default html or custom 404 that would redirect /x/y/z to /html/main.html?route=/x/y/z?

1

There are 1 answers

4
Xan On

You should be able to do it with webRequest API (untested!):

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if(/* condition on details.url */) {
      return {redirectUrl: fix(details.url)};
    }
  }, {
    urls: ["chrome-extension://" + chrome.runtime.id + "/*"]
  }, [
    "blocking"
  ]
);

Note that you'll need webRequest and webRequestBlocking permissions.