JavaScript实现浏览器标签页新消息闪烁提示及多标签页同步方案

作者:像素猫时间:2026-10-29 01:41:19浏览:557

本文介绍如何使用JavaScript实现浏览器标签页标题的新消息闪烁效果,包括显示与清除提示的方法。针对多标签页同时闪烁的问题,提出基于Cookie的同步机制,确保用户查看消息后所有页面能统一取消提示状态。

JavaScript实现浏览器标签页新消息闪烁提示及多标签页同步方案

公司项目中采用了新消息提示功能,旨在向用户直观展示存在未读消息。具体实现逻辑如下代码所示:


var newMessageRemind = {
  _step: 0,
  _title: document.title,
  _timer: null,
  //显示新消息提示
  show: function() {
    var temps = newMessageRemind._title.replace("【   】", "").replace("【新消息】", "");
    newMessageRemind._timer = setTimeout(function() {
      newMessageRemind.show();
      //这里写Cookie操作
      newMessageRemind._step++;
      if (newMessageRemind._step == 3) {
        newMessageRemind._step = 1
      };
      if (newMessageRemind._step == 1) {
        document.title = "【   】" + temps
      };
      if (newMessageRemind._step == 2) {
        document.title = "【新消息】" + temps
      };
    },
    800);
    return [newMessageRemind._timer, newMessageRemind._title];
  },
  //取消新消息提示
  clear: function() {
    clearTimeout(newMessageRemind._timer);
    document.title = newMessageRemind._title;
    //这里写Cookie操作
  }

};

通过调用 newMessageRemind.show(); 方法来触发新消息提示显示。

通过调用 newMessageRemind.clear(); 方法来取消新消息提示。

此外,该基础代码存在一个潜在问题:当用户在同一浏览器中打开多个站点页面时,若收到新消息,所有页面标题都会持续闪烁。即使用户在其中一个页面查看了消息,其他页面的闪烁提示仍不会自动停止。

为解决上述多标签页同步问题,我司采用Cookie存储状态的方式进行处理。当用户在任一页面查看新消息后,系统会更新Cookie状态,从而通知并取消所有其他页面中的标题闪烁提示。

接下来,推荐一段补充代码以实现更丰富的交互效果:


<script>
(function() {
  var OriginTitile = document.title, titleTime;
  document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
      document.title = '死鬼去哪里了!';
      clearTimeout(titleTime);
    } else {
      document.title = '(つェ⊂)咦!又好了!';
      titleTime = setTimeout(function() {
        document.title = OriginTitile;
      },2000);
    }
  });
})();
</script>

注意:上述代码依赖于预加载的jQuery库。可将代码直接放置在页面底部或嵌入到JS文件中执行。

作者最新文章
相关文章
更多