I have this simple user script meant to change some links on a YouTube page:
// ==UserScript==
// @name name
// @description description
// @include https://www.youtube.com/*
// @match https://www.youtube.com/*
// ==/UserScript==
var titles = document.getElementsByClassName("vm-video-title-content");
for (var i=0; i<titles.length; i++) {
titles[i].setAttribute("href", titles[i].getAttribute("href").replace("/edit?o=U&video_id", "watch?v"));
}
The code works when I use it in a bookmarklet or just paste it into console but seems to have no effect in Chrome installed as a user script.
I have tried using window.onload and window.addEventListener() to make the code run after the page is loaded but it didn't help to make the code work.
How to make this code work inside a user script?
Using the metablock @run-at attribute allows you to decide when to inject (and therefore run) the code
As you need to wait for the DOM to finish loading, you would use
// @run-at document-end
but, as this seems to be the default, perhaps you need
// @run-at document-idle
If the code relies on "dynamic" content, being loaded, however - you may well be out of luck and have to either watch for changes in DOM (using MutationObserver)
In this case, you'll want to inject your script as early as possible - maybe even
// @run-at document-start
setTimeout should be the very last resort, if ever!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With