标题闪烁需周期性切换字符串并监听焦点事件:失焦时用setInterval交替设置document.title,获焦时清除定时器并恢复原标题,避免干扰用户且确保节奏可控。

document.title 能直接赋值,但只改标题不等于实现「闪烁」
单纯写 document.title = "新消息" 只能设一次静态值。要「闪烁」,本质是周期性切换两个(或多个)标题字符串,并在页面失焦时启动、获焦时停止。关键不是能不能改,而是改的时机和节奏是否可控。
必须监听 window.onblur / window.onfocus 才能避免干扰用户
用户切走又切回来时,还在闪就非常干扰。所有靠谱的闪烁逻辑都依赖这两个事件:失焦开始闪,获焦立刻恢复原题。注意兼容性写法:
-
window.onblur和window.onfocus是标准方式,现代浏览器都支持 - IE 旧版需补
document.onfocusout/document.onfocusin,但 2026 年基本可忽略 - 别用
visibilitychange替代——它触发太频繁,且标签页后台运行时可能不触发
用 setInterval 而非 setTimeout 递归,避免计时漂移
很多示例用 setTimeout 自调用,容易因 JS 主线程阻塞导致间隔不准。正确做法是用 setInterval + 计数器控制状态轮转:
let originalTitle = document.title;
let isFlashing = false;
let flashTimer = null;
let step = 0;
function startFlash() {
if (isFlashing) return;
isFlashing = true;
flashTimer = setInterval(() => {
step = (step + 1) % 2;
document.title = step === 0 ? '【新消息】' + originalTitle : '【 】' + originalTitle;
}, 800);
}
function stopFlash() {
if (flashTimer) {
clearInterval(flashTimer);
flashTimer = null;
}
document.title = originalTitle;
step = 0;
isFlashing = false;
}
window.onblur = startFlash;
window.onfocus = stopFlash;
移动端和 PWA 场景下 title 闪烁可能无效或被截断
iOS Safari 和部分 Android 浏览器对后台标签页的 JS 执行限制极严,setInterval 在失焦后很快被暂停;PWA 安装后也可能绕过 title 更新。此时闪烁只是“尽力而为”,不能当作可靠通知通道:
- 标题长度超过 32 字符时,Chrome 移动端会截断显示,闪烁文字可能完全看不到
- 不要依赖 title 闪烁做关键业务提示(如支付确认),必须搭配系统通知或 badge
- 若需强提示,优先走
Notification.requestPermission()+new Notification()
&、<)时,直接拼接会导致显示异常。改之前先用 document.title.replace(/&/g, '&').replace(/</g, ' 做一次清洗,否则「【新消息】订单&退款」会显示成乱码。

















