update script to use mutation observer

This commit is contained in:
2022-01-06 22:22:13 -05:00
parent 81f37dc3c0
commit 6b61284849
2 changed files with 59 additions and 15 deletions

View File

@ -1,26 +1,61 @@
// ==UserScript==
// @name Turn off Youtube Autoplay
// @namespace https://bubbletea.dev/
// @version 1.0
// @version 2.0
// @description Disables Youtube recommended videos from automatically playing
// @author shibao
// @include https://www.youtube.com/watch*
// @downloadURL https://gitea.bubbletea.dev/bubbletea.dev/disable-youtube-autoplay/raw/branch/master/disable-youtube-autoplay.user.js
// @updateURL https://gitea.bubbletea.dev/bubbletea.dev/disable-youtube-autoplay/raw/branch/master/disable-youtube-autoplay.user.js
// @downloadURL https://gitea.bubbletea.dev/shibao/disable-youtube-autoplay/raw/branch/stable/disable-youtube-autoplay.user.js
// @updateURL https://gitea.bubbletea.dev/shibao/disable-youtube-autoplay/raw/branch/stable/disable-youtube-autoplay.user.js
// @grant none
// ==/UserScript==
function disableAutoplay() {
var e = document.querySelector('button.ytp-button[data-tooltip-target-id="ytp-autonav-toggle-button"]');
if (e == null) {
console.error('Youtube checkbox could not be found!');
} else {
var isChecked = document.querySelector('.ytp-autonav-toggle-button').getAttribute('aria-checked') == "true";
if (isChecked) e.click();
// from https://developer.mozilla.org/en-US/docs/Web/API/Node#recurse_through_child_nodes
function eachNode(rootNode, callback) {
if (!callback) {
const nodes = []
eachNode(rootNode, function (node) {
nodes.push(node)
})
return nodes
}
if (false === callback(rootNode)) {
return false
}
if (rootNode.hasChildNodes()) {
const nodes = rootNode.childNodes
for (let i = 0, l = nodes.length; i < l; ++i) {
if (false === eachNode(nodes[i], callback)) {
return
}
}
}
}
(function () {
'use strict';
document.onLoad = setTimeout(disableAutoplay, 1000);
}) ();
const observer = new MutationObserver(function (mutationList) {
for (const mutation of mutationList) {
for (const addedNode of mutation.addedNodes) {
// recurses through all child nodes as well
eachNode(addedNode, function (node) {
if (node.nodeName == 'DIV' &&
node.classList.contains('ytp-autonav-toggle-button') &&
node.getAttribute('aria-checked') == "true") {
const button = node.closest("button");
if (button) { setTimeout(() => button.click(), 1000); }
}
});
}
};
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: true
});
})();