简体   繁体   中英

How to detect Internet Explorer on Next.js (SSR)?

There is a project where we use Next.js. In this project, Internet Explorer view is in a very bad state due to various React.js packages. (For example: React-Slick settings, tag etc.)

I'm also thinking of something to check if the browser is IE but unfortunately the " react-device-detect " package didn't work as it is SSR.

Example:

import {isIE} from "react-device-detect" 

<section className="home">
    {isIE ? (
    <div>
      <p>Google Chrome, Firefox, etc...</p>
    </div>
  ) : (
    <div>
      <p>Internet Explorer</p>
    </div>
  )}
</section>

When I do console.log, it understands whether the browser is IE or not, but it does not fulfill its task. For example: If the browser is IE, we want to render "X", but both Chrome and IE render X.)

How can I detect that the browser is Internet Explorer and provide this browser specific control on Next.js (SSR)? Thanks.

The only way to understand on which browser your application will be displayed is to intercept the User-Agent headers in the request that arrives at the Next.js server

The SSR stage has no visibility into what type of browser the user is using.

Why not simply do something like this:

export default function IndexPage({ isIE }) {
  return <div>Hello {isIE ? "IE" : "Modern Browsers"}!</div>;
}

export async function getServerSideProps({ req }) {
  return {
    props: {
      isIE: /MSIE|Trident/.test(req.headers["user-agent"])
    }
  };
}

Or maybe:

import { useEffect, useState } from "react";

export default function IndexPage() {
  const [isIE, setIsIE] = useState(false);

  useEffect(() => {
    setIsIE(/MSIE|Trident/.test(window.navigator.userAgent));
    return () => {};
  }, []);

  return <div>Hello {isIE ? "IE" : "Modern Browsers"}!</div>;
}

PS: IE users generally don't fake the user-agent headers, so the first should work fine for general users. Also, the second method will need efforts (during development) to manually check by running the website on IE as User-Agent Switcher just changes the headers. And, AFAIK services like Google Fonts too just check the headers and send the CSS accordingly. Also, I agree with Keith you should go with feature detection (and fallbacks) instead of selective rendering.

Side Note:

Please read Browser detection using the user agent for why serving different Web pages or services to different browsers is usually a bad idea.

~ MDN

It is possible if you need to detect on client side, with user navigator object. Following function return true if the browner is internet explorer

function isIE() {
  return (
    /MSIE (\d+\.\d+);/.test(navigator.userAgent) ||
    navigator.userAgent.indexOf("Trident/") > -1
  );
}

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