Home > Mobile >  Next.js: Show warning message to IE visitors
Next.js: Show warning message to IE visitors

Time:09-18

My Next.js app is not working on IE.

It shows the blank screen and throws syntax errors on console.

This is ok, with IE soon-to-be discontinued and all, but I want to prevent IE from executing the single line of code upon detecting the browser.

From this answer, I can check if the browser is IE:

if (window.document.documentMode) {
  // IE detected

  document.write('IE is not supported. Please use a modern browser!')
}

Instead of getting the blank screen, users see why the site is not working with the message above.

There are two questions with this approach:

  1. Where to put the code above in Next.js?
  2. How to terminate the app upon executing the code, or is that possible?

Any help would be appreciated.

CodePudding user response:

You shouldn't rely on the Next.js app to display a message on deprecated/unsupported browser, because the code itself may crash on those browsers (lack of polyfills, etc.)

Instead, the only way to properly display a message warning about the outdated browser is to load a JS script async, that doesn't use ES5 features, so that it may work in all browsers (also, it won't slow down your app or increase bundle size, since it's async).

As far as I know _document.js is the earliest place where you can check the browser, since it is rendered once on the first page request.

You can either use external CDN, or create a checkBrowser.js file in the public folder.

Here is my solution.

pages/_document.js

export default class MyDocument extends Document {

  ...

  render() {
    return (
      <Html>
        <Head>
          <script async src="/scripts/checkBrowser.js" />
        </Head>

      ...

      </Html>
    )
  }
}

public/scripts/checkBrowser.js

// if browser is IE, redirect

if (window.document.documentMode) {

  window.location.replace('/outdated.html')
}

public/outdated.html

<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Unsupported browser</title>
  </head>
  <body>
    <p>Internet Explorer (IE) is not supported. Please use a modern browser.</p>
  </body>
</html>

Credit: Script from CDN, Redirect approach, also @YuZhou for sharing those links

  • Related