A quandary: Best way to extract the YouTube video ID of a pre-roll advertisement?

I can do this manually using the following: Right-click on the video player, copy debug info, paste into text editor, and Ctrl+F for “addocid”.

What is the best way to do this automatically?

By modifying an ad accelerator I found, I can reliably detect when a pre-roll ad is playing:


<span style="color:#323232;">function handleVideoAd() {
</span><span style="color:#323232;">	const video = document.querySelector('video');
</span><span style="color:#323232;">	const adElement = document.querySelector('.video-ads.ytp-ad-module');
</span><span style="color:#323232;">	if (video && adElement && adElement.children.length > 0) {
</span><span style="color:#323232;">		alert('advertisement found!')
</span><span style="color:#323232;">	}
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">function initializeAdHandling() {
</span><span style="color:#323232;">	handleVideoAd();
</span><span style="color:#323232;">	const observer = new MutationObserver(handleVideoAd);
</span><span style="color:#323232;">	observer.observe(document.body, { childList: true, subtree: true });
</span><span style="color:#323232;">}
</span><span style="color:#323232;">initializeAdHandling()
</span>

If I had the video ID, I could then open the video in a new tab using something like:

window.open(‘https://www.youtube.com/watch?v=adVideoID’);

However, I am at a bit of a loss as to how to extract the ad video ID itself.

In the browser inspector, the only places I can find the ad video ID are:

  1. Within the URL for ytp-cued-thumbnail-overlay-image
  2. As adVideoId within var ytInitialPlayerResponse, which itself is within <script nonce=“rwc3vYf3vRLEyNQKsJOgig”>, where rwc3vYf3vRLEyNQKsJOgig changes with every video.

What would be the best way to extract the advertisement video ID?

Apologies for if I’m going about this the wrong way. I am (very!) new to JavaScript, but interested in learning. Please let me know if I’ve broken any community rules, or committed any other sort of faux pas. Thanks! :)

  • All
  • Subscribed
  • Moderated
  • Favorites
  • javascript@programming.dev
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • megavids
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • anitta
  • Leos
  • tester
  • provamag3
  • JUstTest
  • All magazines