萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

網頁標題閃爍提示新訊息:跨瀏覽器兼容實現方案

需求背景

Web 應用常需在頁面未聚焦時,透過標題閃爍提醒新訊息(如 Web 版微信、Gmail)。核心挑戰在於跨瀏覽器修改 <title> 內容,尤其 IE 將 title.innerHTML 設為唯讀。

核心難點與解法

瀏覽器修改標題方式備註
Chrome/Firefox/Edgedocument.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 做系統級通知,標題閃爍作為降級方案。
  • 將閃爍頻率、樣式(Emoji、括號風格)參數化。
  • 注意:頻繁修改 document.title 可能影響 SEO 爬蟲抓取,建議僅在 document.hidden 時啟用。
copyright © 萬盛學電腦網 all rights reserved