Javascript 更改标题只保存几秒钟(直到页面停止加载)
我正在尝试更改youtube页面的标题(以便浏览器顶部的选项卡更改为“测试”而不是“youtube”)。它会更改几秒钟,从“youtube”更改为“test”,然后在页面停止加载后恢复为默认的“youtube”。我使用Chrome和tampermonkey扩展来注入代码(也使用jquery)。如何在网页的生命周期内保持更改?代码如下:Javascript 更改标题只保存几秒钟(直到页面停止加载),javascript,jquery,html,tampermonkey,javascript-injection,Javascript,Jquery,Html,Tampermonkey,Javascript Injection,我正在尝试更改youtube页面的标题(以便浏览器顶部的选项卡更改为“测试”而不是“youtube”)。它会更改几秒钟,从“youtube”更改为“test”,然后在页面停止加载后恢复为默认的“youtube”。我使用Chrome和tampermonkey扩展来注入代码(也使用jquery)。如何在网页的生命周期内保持更改?代码如下: // ==UserScript== // @name Hello World App // @namespace http://tamper
// ==UserScript==
// @name Hello World App
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @include *.youtube.*
// @require https://code.jquery.com/jquery-3.3.1.min.js
// ==/UserScript==
var $ = window.jQuery;
$(document).prop('title', 'test');
YouTube几乎肯定会在页面的整个生命周期内动态更改标题,因此它将覆盖您对其所做的任何更改。解决这个问题的唯一方法是定期更改标题,因此setInterval将是您需要的
var $ = window.jQuery;
window.setInterval(function() {
$(document).prop('title', 'test');
}, 1000);
1000表示每1000毫秒或1秒,标题将重置为“测试”。使用MutationObserver检测网站更改标题的确切时刻:
// ==UserScript==
// @name YT title
// @match https://www.youtube.com/*
// @run-at document-start
// ==/UserScript==
if (!checkHead()) {
new MutationObserver((_, ob) => checkHead() && ob.disconnect())
.observe(document.documentElement, {childList: true});
}
function checkHead() {
if (document.head) {
overrideTitle();
return true;
}
}
function overrideTitle(title = 'foo') {
new MutationObserver(() => {
if (document.title !== title) {
document.title = title;
}
}).observe(document.head, {childList: true, characterData: true});
}