Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a JavaScript script before react loads to not render the react app if the browser is Internet Explorer

I want to run a javascript script that detects the user browser and if the browser is IE (not supported by my app, doesn’t plan to – but there are a couple of users who ran into this issue), I want to instead of rendering the app just displaying a message saying browser is not supported etc.

Script is pretty straightforward:

    function isBrowserSupported() {
      var userAgent = window.navigator.userAgent
      var isIE10orLower = userAgent.indexOf("MSIE ")
      var isIE11 = userAgent.indexOf("Trident/")
    
      return !(isIE10orLower > 0 || isIE11 > 0)
    }
    
    if (!isBrowserSupported()) {
      var warningTextElement = document.createElement("span")
      warningTextElement.innerHTML = "<h1>This browser is not supported. Please change it.</h1>"
      document.querySelector("#react-root").removeNode()
      document.querySelector("body").appendChild(warningTextElement)
    }

I am importing the script on the index.html file like that:

    <script type="text/javascript" src="detectUnsupportedBrowsers.js"></script>

With the script I am removing the react-root node which feels a bit hacky, it works but I want to know if there is a better way of doing this (like someplace I can execute a script before react renders?).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

>Solution :

What you have tried is fine. You can conditionally render your app or warning text to the root div in the index.js file instead.

I would try it like below.

import ReactDOM from "react-dom";
import App from "./App";

function isBrowserSupported() {
  var userAgent = window.navigator.userAgent;
  var isIE10orLower = userAgent.indexOf("MSIE ");
  var isIE11 = userAgent.indexOf("Trident/");

  return !(isIE10orLower > 0 || isIE11 > 0);
}

const rootElement = document.getElementById("react-root");

ReactDOM.render(
  <>
    {isBrowserSupported() ? (
      <App />
    ) : (
      <h1>This browser is not supported. Please change it.</h1>
    )}
  </>,
  rootElement
);

Code sandbox => https://codesandbox.io/s/wispy-waterfall-ibzmg?file=/src/index.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading