Youtube API detecting advertisements

泄露秘密 提交于 2021-02-07 04:26:34

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/39985456/youtube-api-detecting-advertisements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!