可使用 navigator.useragent 检测低版本 ie(msie/trident)及 chrome(

可以用 BOM(Browser Object Model)中的 navigator.userAgent 或更现代的 navigator.userAgentData(需配合特性检测)来识别浏览器类型和版本,再结合简单 DOM 操作插入提示条。核心思路是:判断是否为低版本 IE 或旧版 Chrome/Firefox/Safari,满足条件则在页面顶部插入一条醒目的提示信息,并提供关闭按钮和升级引导。
检测低版本浏览器(兼容主流方案)
由于 navigator.userAgentData 兼容性有限(Chrome 101+、Edge 101+,Firefox/ Safari 尚未支持),目前仍推荐用 userAgent 字符串解析 + 特性兜底的方式:
- 优先检测 IE(
MSIE或Trident):IE10 及以下视为过时 - 对 Chrome/Firefox/Safari 做版本截断(如 Chrome
- 补充关键 API 检测(如
Promise、fetch、classList),避免误判伪装 UA 的情况
动态插入提示条 DOM 元素
创建一个固定定位的 <div>,包含文字、关闭按钮和可选的升级链接。注意添加内联样式确保立即生效,不依赖外部 CSS:
<pre class="brush:php;toolbar:false;">const bar = document.createElement('div');
bar.id = 'browser-warning-bar';
bar.innerHTML = `
⚠️ 您的浏览器版本过低,部分功能可能无法正常使用。建议升级到最新版 Chrome、Firefox、Edge 或 Safari。
<button id="close-browser-bar" style="margin-left: 12px; padding: 2px 8px; font-size: 12px; background: #e0e0e0; border: none; border-radius: 3px; cursor: pointer;">×</button>
`;
bar.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #fff3cd;
color: #856404;
text-align: center;
padding: 8px 0;
font-size: 14px;
z-index: 9999;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
`;
document.body.insertBefore(bar, document.body.firstChild);
</pre>
<h3>绑定关闭与持久化逻辑</h3>
<p>点击 × 按钮隐藏提示条,并通过 <code>localStorage 记录用户选择,避免重复打扰:
- 给关闭按钮添加
click事件,调用bar.remove() - 同时设置
localStorage.setItem('browserWarningClosed', 'true') - 初始化时先检查
localStorage和 UA 条件,仅当未关闭且命中低版本才显示
推荐的最小可用实现(直接粘贴到 或 底部)
以下代码已兼顾兼容性、轻量和可维护性:
(function() {
const closed = localStorage.getItem('browserWarningClosed') === 'true';
if (closed) return;
function isOutdated() {
const ua = navigator.userAgent;
// IE 10 及以下
if (ua.indexOf('MSIE ') > -1 || ua.indexOf('Trident/') > -1) return true;
// Chrome ×';
bar.style.cssText = 'position:fixed;top:0;left:0;width:100%;background:#fff3cd;color:#856404;text-align:center;padding:8px 0;font-size:14px;z-index:9999;box-shadow:0 2px 4px rgba(0,0,0,0.1);';
const closeBtn = bar.querySelector('#close-browser-bar');
closeBtn.addEventListener('click', () => {
bar.remove();
localStorage.setItem('browserWarningClosed', 'true');
});
document.body.insertBefore(bar, document.body.firstChild);
})();











