Web 應用常需在頁面未聚焦時,透過標題閃爍提醒新訊息(如 Web 版微信、Gmail)。核心挑戰在於跨瀏覽器修改 <title> 內容,尤其 IE 將 title.innerHTML 設為唯讀。
| 瀏覽器 | 修改標題方式 | 備註 |
|---|---|---|
| Chrome/Firefox/Edge | document.title = '新標題' 或 titleEl.innerHTML = '...' | 均支援 |
| IE (≤11) | document.title = '新標題' | title.innerHTML 唯讀,強寫拋錯 |
策略:嘗試使用 titleEl.innerHTML(可精確控制全形/半形空格寬度),捕獲異常後降級為 document.title。
<script>
var flashTitlePlayer = {
start: function(msg) {
this.title = document.title;
if (!this.action) {
try {
this.element = document.getElementsByTagName('title')[0];
this.element.innerHTML = this.title; // 初始化
this.action = function(ttl) { this.element.innerHTML = ttl; };
} catch (e) {
this.action = function(ttl) { document.title = ttl; };
delete this.element;
}
this.toggleTitle = function() {
this.action('【' + this.messages[this.index = this.index == 0 ? 1 : 0] + '】歡迎訪問示例頁');
};
}
// 計算空格長度:全形字佔 2 寬度,半形佔 1
this.messages = [msg];
var n = msg.length, s = '';
if (this.element) { // 僅 innerHTML 模式需精確空格
var halfWidth = msg.match(/[^\u4e00-\u9fa5]/g); // 簡易判斷半形字
if (halfWidth) {
var hw = halfWidth.length;
n -= hw;
while (hw-- > 0) s += ' '; // 半形空格
}
}
while (n-- > 0) s += ' '; // 全形空格 U+3000
this.messages.push(s);
this.index = 0;
this.timer = setInterval(() => this.toggleTitle(), 1000);
},
stop: function() {
if (this.timer) {
clearInterval(this.timer);
this.action(this.title); // 還原原標題
delete this.timer;
delete this.messages;
}
}
};
function flashTitle(msg) { flashTitlePlayer.start(msg); }
function stopFlash() { flashTitlePlayer.stop(); }
</script>
<!-- 收到新訊息時 -->
<script> flashTitle('您有 3 條新訊息'); </script>
<!-- 用戶點擊頁面/切換標籤頁時 -->
<script> stopFlash(); </script>
Page Visibility API (document.visibilityState) 自動控制啟停。Notification API 做系統級通知,標題閃爍作為降級方案。document.title 可能影響 SEO 爬蟲抓取,建議僅在 document.hidden 時啟用。