Next.js: 向 IE 访问者显示警告信息
Next.js: Show warning message to IE visitors
我的 Next.js 应用无法在 IE 上运行。
它显示空白屏幕并在控制台上抛出语法错误。
没关系,IE 即将停产,但我想阻止 IE 在检测到浏览器时执行单行代码。
从this answer开始,我可以检查浏览器是不是IE:
if (window.document.documentMode) {
// IE detected
document.write('IE is not supported. Please use a modern browser!')
}
用户不会看到空白屏幕,而是会看到网站无法使用上述消息的原因。
这种方法有两个问题:
- 将上面的代码放在Next.js的什么地方?
- 如何在执行代码时终止应用程序,或者这可能吗?
如有任何帮助,我们将不胜感激。
您不应依赖 Next.js 应用程序在 deprecated/unsupported 浏览器上显示消息,因为代码本身可能会在这些浏览器上崩溃(缺少 polyfill 等)
相反,正确显示有关过时浏览器的消息警告的唯一方法是异步加载 JS 脚本,它不使用 ES5+ 功能,因此它可以在所有浏览器中工作(而且,它不会'不要减慢您的应用程序或增加包大小,因为它是异步的)。
据我所知,_document.js
是最早可以检查浏览器的地方,因为它在第一个页面请求时呈现一次。
您可以使用外部 CDN,或在 public
文件夹中创建一个 checkBrowser.js
文件。
这是我的解决方案。
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>
来源:Script from CDN, Redirect approach,还有@YuZhou 分享了这些链接
我的 Next.js 应用无法在 IE 上运行。
它显示空白屏幕并在控制台上抛出语法错误。
没关系,IE 即将停产,但我想阻止 IE 在检测到浏览器时执行单行代码。
从this answer开始,我可以检查浏览器是不是IE:
if (window.document.documentMode) {
// IE detected
document.write('IE is not supported. Please use a modern browser!')
}
用户不会看到空白屏幕,而是会看到网站无法使用上述消息的原因。
这种方法有两个问题:
- 将上面的代码放在Next.js的什么地方?
- 如何在执行代码时终止应用程序,或者这可能吗?
如有任何帮助,我们将不胜感激。
您不应依赖 Next.js 应用程序在 deprecated/unsupported 浏览器上显示消息,因为代码本身可能会在这些浏览器上崩溃(缺少 polyfill 等)
相反,正确显示有关过时浏览器的消息警告的唯一方法是异步加载 JS 脚本,它不使用 ES5+ 功能,因此它可以在所有浏览器中工作(而且,它不会'不要减慢您的应用程序或增加包大小,因为它是异步的)。
据我所知,_document.js
是最早可以检查浏览器的地方,因为它在第一个页面请求时呈现一次。
您可以使用外部 CDN,或在 public
文件夹中创建一个 checkBrowser.js
文件。
这是我的解决方案。
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>
来源:Script from CDN, Redirect approach,还有@YuZhou 分享了这些链接