基本上我希望擴展程式做的是,當我打開一個 youtube 視頻時,獲取 youtube 頻道的名稱并將其添加到視窗標題中,這樣我就可以只阻止某些頻道的 youtube 視頻。因此,如果 youtube 頻道名稱是“Mark Rober”,視頻標題(以及視窗標題)是“NASA 是在浪費錢嗎?” 我想將視窗標題更改為“NASA 是在浪費錢嗎? - Mark Rober”。
我嘗試為此撰寫一個 chrome 擴展,但我不知道如何獲取 youtube 頻道的名稱以將其放入視窗標題中。我嘗試使用 document.querySelector 和 document.getElementById 并且都回傳“null”或未定義。可能是因為我不知道如何專門訪問頻道名稱,因為它在 HTML 中并沒有真正的唯一 ID。
我還考慮過通過 YouTube API 執行此操作,但這需要 OAuth 令牌。而且由于這個擴展與許多網路攔截器一起使用真的很有幫助,我很樂意在它作業時分享它,并且使用可能不太容易訪問的令牌(我認為)。
因此,如果有人可以幫助我做到這一點,我將非常感激:)
uj5u.com熱心網友回復:
我不確定他們的代碼中發生了什么,也許 ID 不是唯一的或其他什么,但無論如何,我已經設法使用最丑陋的運算式來獲取頻道的名稱:
document.getElementById("primary-inner").children[7].children[1].children[0].children[0].children[0].children[0].children[1].children[0].children[0].children[0].children[0].children[0].innerHTML
(您是否知道頁面加載需要時間的問題,如果腳本在頁面完成加載之前運行,您可能會得到null?有一些技術可以克服這個問題,以防它對您來說是新的。)
編輯:
適用于我的 Chrome 擴展程式的完整代碼:
displayChannelName.js:
console.log("displayChannelName started.");
let nodeLoaded = setInterval(function () {
let node = document.getElementById("primary-inner");
if (node != undefined) {
let channelName = node.children[7].children[1].children[0].children[0].children[0].children[0].children[1].children[0].children[0].children[0].children[0].children[0].innerHTML;
console.log("channel name: " channelName);
document.title = document.title " - " channelName;
clearInterval(nodeLoaded);
};
}, 500);
manifest.json:
{
"name": "YouTube Channel Name",
"version": "1",
"description": "Display YouTube Channel Name",
"manifest_version": 3,
"content_scripts": [ {
"matches": ["https://www.youtube.com/watch*"],
"js": ["displayChannelName.js"]
} ]
}
編輯:
使用 MutationObserver:
displayChannelName.js:
console.log("displayChannelName script started.");
let currTitle;
function updateTitle(node) {
if (document.title != currTitle) {
console.log("updateTitle function called.");
if (node == undefined) {
node = document.getElementById("primary-inner");
};
setTimeout(function () { // wait a little in case title changes before the node reloads
let channelName = node.children[7].children[1].children[0].children[0].children[0].children[0].children[1].children[0].children[0].children[0].children[0].children[0].innerHTML;
document.title = " - " channelName;
currTitle = document.title;
}, 500);
};
};
let nodeLoaded = setInterval(function () {
// update title on page load
let node = document.getElementById("primary-inner");
if (node != undefined) {
updateTitle(node);
clearInterval(nodeLoaded);
};
}, 500);
// listen for future changes
new MutationObserver(function (mutations) {
updateTitle(undefined);
}).observe(
document.querySelector("title"),
{ subtree: true, characterData: true, childList: true }
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/428344.html
