You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在网页URL变化时修改网页标题?

解决方案:仅在URL变化时允许更新网页标题

你的问题核心是既要阻止网站频繁修改标题(比如添加通知数量),又要在URL变化时(比如播放列表切换视频)正常更新标题。原来的代码直接锁死了document.title的可写性,导致所有修改都被禁止,显然过度限制了功能。

下面是针对性的实现方案:

核心思路

  • 跟踪URL的变化(覆盖单页应用的pushState/replaceState操作和哈希变化场景)
  • 重写document.title的setter逻辑:仅当URL发生变化时,允许更新标题;其余场景忽略修改请求
  • 维护当前URL和合法标题的状态,确保只有URL变更触发的标题更新生效

代码实现

// 初始化记录当前URL和页面标题
let currentUrl = window.location.href;
let validTitle = document.title;

// 重定义document.title的读写逻辑
Object.defineProperty(document, 'title', {
  get() {
    return validTitle;
  },
  set(newTitle) {
    // 仅当URL发生变化时,允许更新标题
    if (window.location.href !== currentUrl) {
      validTitle = newTitle;
      currentUrl = window.location.href;
      // 调用原生title的setter完成真实更新
      const nativeTitleSetter = Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'title').set;
      nativeTitleSetter.call(document, newTitle);
    }
    // URL未变化时,直接忽略所有标题修改请求
  },
  enumerable: true,
  configurable: true
});

// 监听单页应用的URL变更(pushState/replaceState不会触发popstate事件,需手动拦截)
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;

history.pushState = function(...args) {
  originalPushState.apply(this, args);
  currentUrl = window.location.href;
};

history.replaceState = function(...args) {
  originalReplaceState.apply(this, args);
  currentUrl = window.location.href;
};

// 监听哈希变化场景
window.addEventListener('hashchange', () => {
  currentUrl = window.location.href;
});

代码说明

  1. URL状态跟踪:通过currentUrl变量实时记录当前页面的URL,确保能准确判断URL是否发生变化
  2. 自定义title setter:拦截所有标题修改请求,仅在URL变化的场景下执行真实更新,避免无关的标题变更(比如通知数量更新)
  3. 单页应用适配:重写pushState和replaceState方法,覆盖单页应用无刷新跳转的URL变更场景
  4. 哈希变化处理:监听hashchange事件,兼容通过哈希值变化实现的页面跳转

这个方案可以精准控制标题更新时机:播放列表切换视频(URL变化)时标题正常更新,而网站频繁添加通知数的无效标题修改会被直接拦截。

内容的提问来源于stack exchange,提问作者Mike Dasik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:13:13