简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM