如何使用用户脚本更改标题?

问题描述 投票:0回答:1

我正在尝试更改 twitter 的标题,因为他们将其更改为包含 X,但从我可以在堆栈溢出和 Github 等上收集到的所有内容来看,这是通过使用

document.title
来做到这一点的方法,但是当我尝试时这样做是行不通的,它不仅不会改变标题,它甚至不想获得标题(让它用
console.log
输出标题和new_title,但什么也没有输出)

var title = document.title;
if (title.endsWith("/ X")) {
  var new_title = title.slice(0, -3) + "/ Twitter";
  document.title = new_title;
}

这是完整的代码,以防脚本的其余部分出现问题https://gist.github.com/biast12/04f66af3297b9395ec489f7eb16a9286/https://gist.github.com/biast12/04f66af3297b9395ec489f7eb16a9286 /原始/替换-twitter-logo.user.js

javascript twitter userscripts
1个回答
0
投票

因为 Twitter 是一个 JS 应用程序,所以它会在用户导航时动态更改标题。标题也会在初始页面加载后稍稍注入到页面中。目前,这意味着当您检查

document.title
时,Twitter 应用程序客户端尚未设置它。

为了解决这个问题,我们需要捕获:

  1. 当标题元素首次添加到页面时。
  2. 对该标题元素的所有后续更改。

可以用

MutationObserver
来完成:

function fixTitle() {
  var title = document.title;

  if (title === "X") {
    document.title = "Twitter";
  }

  if (title.endsWith("/ X")) {
    var new_title = title.slice(0, -3) + "/ Twitter";
    document.title = new_title;
  }
}

window.addEventListener("load", function () {
  new MutationObserver(function (mutations) {
    // Ignore changes to <head> apart from when <title> is added
    if (
      !mutations.some((mutation) =>
        [...mutation.addedNodes].some((node) => node.nodeName === "TITLE"),
      )
    )
      return;

    // Fix initially added title
    fixTitle();

    // Watch the new title element for any change now it exists
    new MutationObserver(function () {
      fixTitle();
    }).observe(document.querySelector("title"), {
      characterData: true,
      attributes: true,
      childList: true,
      subtree: true,
    });
  }).observe(document.querySelector("head"), { childList: true });
});

我注意到页面加载时仍然有

X
的闪烁,因为它首先将标题放入
X
,然后将其更改为
[page] / X
格式。所以我还添加了一个额外的条件来检查这一点。

我们在这件事上有共同的奉献精神😂。请随意在您的公共脚本中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.