Ad

GreaseMonkey + Youtube + .click()

- 1 answer

Goal: I load a YouTube playlist then GreaseMonkey click()s the "shuffle playlist" button.

I can run these two lines straight in my console and it works perfectly:

var shuffleBtn = document.querySelector(".yt-uix-button.shuffle-playlist");
shuffleBtn.click();

However, when I tried to move it into GreaseMonkday, it no longer works. The console.log's in the code below do run-- and the (commented out) remove() works, but the click() will not trigger. I've also tried the method outlined here, sans the jQuery bits, but no luck either.

What am I missing?

// ==UserScript==
// @name        YouTube - Randomize Playlist
// @namespace   ytplaylistrandom
// @include     https://www.youtube.com/watch?v=yyDUC1LUXSU&list=PLh6vppUwmWEMdp04u-tYABoDmgn9AX12n
// @version     1
// @grant       none
// ==/UserScript==

window.onload = function () {
    var shuffleBtn = document.querySelector(".yt-uix-button.shuffle-playlist");
    if( shuffleBtn ){
      console.log('exists');
      shuffleBtn.click();
      //shuffleBtn.remove();
      console.log('end');
    }else {
      console.log('nobutton');
    }
}
Ad

Answer

I think I got it:

Use window.addEventListener("load", function(){}) instead of window.onload = function(){}.

It seems that the window already has an onload function which initializes the functionality of the shuffle button and the script is overriding it.

Ad
source: stackoverflow.com
Ad