I have a YouTube playlist displayed inside an iframe on a webpage & want to automate clicking on the playlist’s ‘index button’ when the page loads so that the list of videos is displayed.
The button has the following classes: ytp-playlist-menu-button
& ytp-button
but no ID. It does however have an aria-owns
ytp-id-22
which after Googling, I believe acts like an ID – is that right?
As I’m not sure whether aria-owns
acts like (& can be used as) an ID, I’m trying document.getElementsByClassName
instead but am aware that this is not a good practice & doesn’t work on some browsers.
I’m trying to work out by looking at examples online but haven’t found a clear way to achieve this. I’m currently using the script formula below but it doesn’t work & I’m not convinced it’s the right approach either.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#player_2').contentWindow
document.getElementsByClassName('ytp-playlist-menu-button').trigger("click") ;
});
You can view the actual page where the YouTube playlist is embedded here
My knowledge of writing javascript / jQuery is extremely limited but as far as I understand it, in the above code:
- The 1st line ensures the page has fully loaded
- The 2nd line allows it work ‘inside’ an iframe (with the ID ‘player_2’)
- The 3rd line is the action that clicks on the button (with an ID ‘ytp-playlist-menu-button’)
Also just to say:
A. Above is the entire script & I was wondering does it need additional code to actually work properly?
B. I have enqueued the script into the header via this code:
function theme_enqueue_scripts() {
if (is_page ('3055') ) {
wp_enqueue_script ('youtubePlaylistButton_js', get_theme_file_uri() . '/wp-includes/js/youtubePlaylistButton_js.js', array(), false, false); }
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );