Reputation: 1937
Is there a way to detect a youtube advertisement, when it is playing and also when it ends?
Something like:
function onPlayerStateChange(event) {
if(event.data == advertisement) {
console.log("Advertisement is playing");
}
if(event.data == advertisementIsOver) {
console.log("Advertisement has finished playing");
}
}
I see the question here:
What is the YouTube's PlayerState during pre-roll ad?
And am wondering if there are any updates to the youtube api? Also, can someone provide some code of a youtube advertisement detector? I am not sure how one reliably catches when an advertisement is playing.
Upvotes: 3
Views: 5885
Reputation: 703
A little late but better late than never...
I'm currently developing a chrome extension specifically targeted towards YouTube video playback manipulation. This is one method I've found to detect whether an ad is playing:
Note: All classes I use and Id's are subject to change as YouTube developers change them.
1) Get the html5 video element first: var mainVideo = document.getElementByClassName("html5-main-video")
. No element Id for it at the moment but it always has the class html5-main-video
.
2) Set an event handler for when the video is ready to play that will check whether or not it's an ad and will be fired when a new video is loaded and ready to play mainVideo.oncanplay = isVideoAnAd
.
3) When an ad is playing the progress bar is yellow or more specifically rgb(255, 204, 0)
and this property is easily comparable using jQuery
function isVideoAnAd () {
if($(".ytp-play-progress").css("background-color") === "rgb(255, 204, 0)
{
return true;
}}
For more reliable results you can also check the movie_player
elements classList
to see if it contains("ad-showing")
. By the way, movie_player
is the id.
Tip: I found all of this with inspect element
This is really the only reliable way I've found to detect ads without having to dive into the YouTube API.
Upvotes: 10
Reputation: 13469
You might want to check this documentation. It is stated that you can use onAdStarted()
which is called when playback of an advertisement starts.
Here is a related forum and tutorial which might help.
Upvotes: -1