Quiero ejecutar un script javascript que detecte el navegador del usuario y si el navegador es IE (no es compatible con mi aplicación, no planea hacerlo, pero hay un par de usuarios que se encontraron con este problema), quiero en lugar de renderizar la aplicación simplemente mostrando un mensaje que dice que el navegador no es compatible, etc.
El guión es bastante sencillo:
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> Con la secuencia de comandos, estoy eliminando el nodo react-root que se siente un poco extraño, funciona, pero quiero saber si hay una mejor manera de hacerlo (¿algún lugar donde pueda ejecutar una secuencia de comandos antes de que se renderice la reacción?).
Gracias.
Lo que has probado está bien. En su lugar, puede renderizar condicionalmente su app o warning text en el div root en el archivo index.js .
Lo intentaría como a continuación.
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 );Zona de pruebas de código => https://codesandbox.io/s/wispy-waterfall-ibzmg?file=/src/index.js