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?).
Thank you.
CodePudding user response:
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