This is a note on monitoring YouTube URL changes with JavaScript.
Since YouTube uses asynchronous communication when navigating between videos, user scripts can be difficult to use.
When you want to re-execute a script when the HTML (= video) changes, monitoring URL changes seems to be a good approach…
Normally, hashchange should work:
window.onhashchange = function() {
console.log('y')
}
window.addEventListener('hashchange', function(e){console.log('hash changed')});
document.addEventListener("hashchange", function(){cosole.log('y')});
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
But it doesn’t seem to work on YouTube, so you have to do it like this.
var youtubeUrl = setInterval(function(){console.log(document.location.href)} , 1000)
Example of checking for URL changes every second and processing when a change occurs:
// Processing *1
var youtubeUrlPrevious = document.location.href
var youtubeUrl = setInterval(function(){
if (document.location.href==youtubeUrlPrevious){
} else {
// Processing *2
youtubeUrlPrevious = document.location.href
}
} , 1000)
Processing 1 is the processing you want to do before the URL changes Processing 2 is the processing executed when the URL changes So, basically, you should write the same processing in Processing 1 and 2.