IMA HTML5 SDK는 완전 자동화된 광고 재생목록을 지원합니다. 이 기능은 광고를 트래피킹할 때 Google Ad Manager에 지정된 대로 콘텐츠에 광고 시점을 삽입합니다. 또한 프리롤, 미드롤, 포스트롤을 비롯한 광고 시점을 지원하는 데 필요한 동영상 플레이어 코드를 크게 간소화합니다.
AdsManager를 만들 때 getAdsManager 호출을 사용하여 contentPlayback 객체가 전달됩니다. 이 객체에는 동영상의 현재 재생 헤드 위치를 반환하는 currentTime 속성이 있어야 합니다. HTML5 video 요소를 사용하여 콘텐츠를 표시하는 경우 해당 요소를 SDK에 전달하기만 하면 됩니다. 이 객체는 콘텐츠 재생 진행률을 추적하여 Ad Manager에 지정된 시간에 광고 시점이 자동으로 삽입되도록 하는 데 사용됩니다. 또한 SDK가 개발자를 대신하여 콘텐츠 상태를 처리하도록 하려면 SDK에 이를 알려야 합니다.
varadsRenderingSettings=newgoogle.ima.AdsRenderingSettings();adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete=true;adsManager=adsManagerLoadedEvent.getAdsManager(videoContent,adsRenderingSettings);// See API reference for contentPlayback.
포스트롤이 재생되도록 하려면 콘텐츠가 완료되었음을 SDK에 알려야 합니다. SDK가 동영상 플레이어를 사용하여 광고를 재생하는 경우도 있으므로 이 작업은 약간 까다롭습니다. 따라서 광고가 종료된 것이 아니라 콘텐츠가 종료되었을 때만 SDK에 알리도록 해야 합니다. 다음 코드를 사용하여 할 수 있습니다.
동영상 플레이어가 드래그 투 탐색을 지원하고 사용자가 드래그하는 동안 동영상 플레이어의 현재 시간 속성이 업데이트되면 SDK는 정상적으로 진행되는 콘텐츠와 사용자가 콘텐츠를 탐색하는 것을 구분할 수 없습니다. 맞춤 contentPlayback 객체를 getAdsManager의 매개변수로 사용해야 합니다. 이 사용 사례의 예는 탐색 관련 문제를 참고하세요.
참고: 콘텐츠 재생이 완료되었거나 사용자가 재생을 중지한 경우 SDK에 콘텐츠가 완료되었음을 알리기 위해 AdsLoader.contentComplete를 호출해야 합니다. 그러면 SDK는 포스트롤 광고 시점(예약된 경우)을 재생합니다. ALL_ADS_COMPLETED 이벤트는 모든 광고 시점이 재생될 때 발생합니다. 또한 init()가 호출될 때 콘텐츠 추적이 시작되며 콘텐츠를 재생하기 전에 항상 init()를 호출해야 합니다.
광고 시점의 자동 재생 사용 중지
경우에 따라 준비가 될 때까지 SDK가 광고 시점을 재생하지 못하도록 할 수 있습니다. 이 시나리오에서는 광고 시점의 자동 재생을 사용 중지하고 광고 시점 재생 준비가 되면 SDK에 알릴 수 있습니다. 이 구성을 사용하면 SDK가 광고 시점을 로드하면 AD_BREAK_READY 이벤트가 실행됩니다. 플레이어에서 광고 시점이 시작될 준비가 되면 adsManager.start()를 호출할 수 있습니다.
functionrequestAds(){}...adsLoader.getSettings().setAutoPlayAdBreaks(false);...}functiononAdsManagerLoaded(){...// For non-auto ad breaks, listen for ad break readyadsManager.addEventListener(google.ima.AdEvent.Type.AD_BREAK_READY,adBreakReadyHandler);...}functionadBreakReadyHandler(){// Once we're ready to play ads. To skip this ad break, simply return// from this handler without calling adsManager.start().adsManager.start();}
사용해 보기
작동하는 구현은 다음 코드를 참고하세요.
구하는 데 어려움
광고 규칙을 사용하는 경우 클릭 및 드래그 탐색에 문제가 발생할 수 있습니다. 특히 사용자가 클릭하고 드래그하여 동영상에서 여러 미드롤 광고 모음을 지나간 후 콘텐츠가 재개되기 전에 이러한 광고 모음이 2개 이상 연속으로 재생될 수 있습니다. 이는 사용자가 탐색하는 동안 동영상 재생 헤드 시간이 업데이트되기 때문에 발생합니다. 사용자가 광고를 지나 탐색하는 동안 SDK가 현재 시간을 폴링하면 광고를 재생해야 한다고 생각할 수 있습니다. 콘텐츠가 재개되면 해당 광고가 재생된 후 탐색 이후의 가장 최근 광고가 재생됩니다. 이 문제를 시각적으로 표현한 다이어그램은 다음을 참고하세요.
사용자가 탐색을 시작할 때 현재 시간을 저장하고 사용자가 일반 재생을 재개할 때까지 SDK에서 요청할 때 해당 시간을 보고합니다. 이 솔루션의 시각적 표현은 다음 다이어그램을 참고하세요.
이 솔루션을 사용하면 0:10 미드롤을 제대로 건너뛰고 0:20 미드롤만 재생할 수 있습니다. 다음 코드 스니펫에서 맞춤 재생 헤드 추적기를 사용하여 이 작업을 실행합니다. 이 코드에는 다운로드 페이지에서 제공되는 고급 HTML5 샘플의 ads.js 수정사항 (굵게 표시됨)이 포함되어 있습니다.
이 방법은 모바일 Safari를 제외한 모든 플랫폼에서 작동합니다. 모바일 Safari에서는 동영상 태그의 탐색 속성이 올바르게 구현되지 않습니다 (항상 false를 반환함). 이 문제를 해결하려면 사용자가 동영상을 탐색하는지 직접 확인해야 합니다. 이 메서드의 샘플 코드는 다음과 같습니다. 강조 표시된 줄은 기존 코드의 수정사항입니다.
varAds=function(application,videoPlayer){...this.currentTime=0;setInterval(this.updateCurrentTime,1000);this.seeking=false;this.seekCheckInterval=1000;// You may need to adjust this value, depending on your platformthis.seekThreshold=100;this.previousTime=0;setInterval(Application.bind(this,this.checkForSeeking),this.seekCheckInterval);};Ads.prototype.updateCurrentTime=function(){if(!this.seeking){this.currentTime=this.videoPlayer_.contentPlayer.currentTime;}};Ads.prototype.checkForSeeking=function(){varcurrentTime=this.videoPlayer_.contentPlayer.currentTime;// How much time has passed since you last ran this method, in millisecondsvardiff=(currentTime-this.previousTime)*1000;// If that difference is greater than the time since you last ran this method,// plus the threshold, the user was seekingif(Math.abs(diff)>this.interval+this.threshold){this.seeking=true;}else{this.seeking=false;}// Grab the current video time again to make up for time spent in this methodpreviousTime=this.videoPlayer_.contentPlayer.currentTime;};Ads.prototype.onAdsManagerLoaded_=function(adsManagerLoadedEvent){this.application_.log('Ads loaded.');this.adsManager_=adsManagerLoadedEvent.getAdsManager(this);this.processAdsManager_(this.adsManager_);};
이렇게 변경하면 SDK는 콘텐츠 동영상 플레이어의 currentTime 속성이 아닌 Ads 객체의 currentTime 속성을 사용하여 광고 시점을 결정합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-17(UTC)"],[[["\u003cp\u003eThe IMA HTML5 SDK enables automated ad playlists, simplifying ad integration and supporting pre-rolls, mid-rolls, and post-rolls by leveraging Google Ad Manager.\u003c/p\u003e\n"],["\u003cp\u003eTo ensure proper ad playback, developers must signal content completion using \u003ccode\u003eAdsLoader.contentComplete()\u003c/code\u003e and manage content state synchronization with the SDK.\u003c/p\u003e\n"],["\u003cp\u003eCustom content playback objects can be used to address seeking issues and provide finer control over ad break timing and behavior.\u003c/p\u003e\n"],["\u003cp\u003eThe SDK provides events like \u003ccode\u003eCONTENT_PAUSE_REQUESTED\u003c/code\u003e, \u003ccode\u003eCONTENT_RESUME_REQUESTED\u003c/code\u003e, and \u003ccode\u003eAD_BREAK_READY\u003c/code\u003e for developers to manage content playback and ad interactions.\u003c/p\u003e\n"],["\u003cp\u003eSpecific code adjustments are necessary to handle seeking accurately on mobile Safari due to platform limitations.\u003c/p\u003e\n"]]],[],null,["IMA HTML5 SDK supports fully automated ad playlists. This feature\ninserts ad breaks into the content as specified in\n[Google Ad Manager](//www.google.com/dfp)\nwhen trafficking your ads. It also greatly simplifies the video player code\nnecessary to support ad breaks, including pre-rolls, mid-rolls and post-rolls.\n\n- When creating the `AdsManager`, a `contentPlayback` object is passed in using the [getAdsManager](/interactive-media-ads/docs/sdks/html5/client-side/reference/interface/google.ima.AdsManagerLoadedEvent#google.ima.AdsManagerLoadedEvent.getAdsManager) call. This object must have a `currentTime` property that returns the current playhead position of the video. If you're using an HTML5 `video` element to display your content, you can just pass that element to the SDK. This object is used to track the progress of the content playback so ad breaks are automatically inserted at the times specified in Ad Manager. You also need to let the SDK know that you want it to handle content state on your behalf. \n\n ```javascript\n var adsRenderingSettings = new google.ima.AdsRenderingSettings();\n adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n adsManager = adsManagerLoadedEvent.getAdsManager(\n videoContent, adsRenderingSettings); // See API reference for /interactive-media-ads/docs/sdks/html5/client-side/reference/interface/google.ima.AdsManagerLoadedEvent#google.ima.AdsManagerLoadedEvent.getAdsManager.\n ```\n- To ensure post-rolls are played, you need to let the SDK know when your content is finished. This is a bit tricky, because in some cases the SDK uses your video player to play ads, so you need to make sure you're only letting the SDK know when your content is finished, and not when an ad is finished. You can do that using the following code: \n\n ```javascript\n var videoContent = document.getElementById('contentElement');\n var contentEndedListener = function() {adsLoader.contentComplete();};\n\n videoContent.addEventListener('ended', contentEndedListener);\n\n function onContentPauseRequested() {\n contentElement.removeEventListener('ended', contentEndedListener);\n ...\n }\n\n function onContentResumeRequested() {\n contentElement.addEventListener('ended', contentEndedListener);\n ...\n }\n ```\n- The [CONTENT_PAUSE_REQUESTED](/interactive-media-ads/docs/sdks/html5/client-side/reference/namespace/google.ima.AdEvent#google.ima.AdEvent.Type) and [CONTENT_RESUME_REQUESTED](/interactive-media-ads/docs/sdks/html5/client-side/reference/namespace/google.ima.AdEvent#google.ima.AdEvent.Type) events are used to pause and resume the content when ad breaks are played.\n- If your video player supports drag-to-seek, and the current time property of the video player updates while the user is dragging, the SDK can't differentiate between content progressing normally and a user seeking through the content. You must use a custom contentPlayback object as your parameter to `getAdsManager`. For an example of this use case, see [The Trouble with Seeking](#trouble-with-seeking).\n\n**Note:** When the content has finished playing or\nthe user has stopped playback, be sure to call AdsLoader.contentComplete\nin order to signal to the SDK that the content is done. The SDK then plays\nthe post-roll ad break, if one has been scheduled. The `ALL_ADS_COMPLETED`\nevent is raised when ALL ad breaks have been played. In addition, note\nthat content tracking begins when `init()` is called and you should\nalways call `init()` before playing content.\n\nDisable automatic playback of ad breaks\n\nIn some circumstances you may want to prevent the SDK from playing ad breaks until\nyou're ready for them. In this scenario, you can disable automatic playback of ad breaks\nin favor of letting the SDK know when you're ready for an ad break to play. With this\nconfiguration, once the SDK has loaded an ad break, it fires an\n`AD_BREAK_READY` event. When your player is ready for the ad break to start,\nyou can call adsManager.start(): \n\n```javascript\nfunction requestAds() {}\n ...\n adsLoader.getSettings().setAutoPlayAdBreaks(false);\n ...\n}\n\nfunction onAdsManagerLoaded() {\n ...\n // For non-auto ad breaks, listen for ad break ready\n adsManager.addEventListener(\n google.ima.AdEvent.Type.AD_BREAK_READY,\n adBreakReadyHandler);\n ...\n}\n\nfunction adBreakReadyHandler() {\n // Once we're ready to play ads. To skip this ad break, simply return\n // from this handler without calling adsManager.start().\n adsManager.start();\n}\n```\n\nTry it out\n\nSee the following code for a working implementation.\nSee the Pen \\\u003ca href='http://codepen.io/imasdk/pen/QyBNrq/'\\\u003eManual Ad Breaks\\\u003c/a\\\u003e by IMA SDK (\\\u003ca href='http://codepen.io/imasdk'\\\u003e@imasdk\\\u003c/a\\\u003e) on \\\u003ca href='http://codepen.io'\\\u003eCodePen\\\u003c/a\\\u003e.\n\nThe trouble with seeking\n\nIf you use ad rules, you may run into a problem with click-and-drag seeking.\nSpecifically, after a user clicks and drags to seek through video past multiple\nmidroll pods, they may see 2 or more of those pods play back to back before\ncontent resumes. This is caused by the video playhead time updating while the\nuser is seeking; if the SDK happens to poll for the current time while the user\nseeks past an ad, it may think that ad should be played. When the content\nresumes, it plays that ad, and then the most recent ad since the seek. For a\nvisual representation of this problem, see the following diagram:\n\nSave the current time when the user starts seeking, and report that time when the SDK\nasks for it until the user resumes normal playback. For a visual representation of this\nsolution, see the following diagram:\n\nWith this solution, you properly skip the 0:10 mid-roll and only play the 0:20 mid-roll.\nThis is done using a custom playhead tracker in the following code snippet. This code\ncontains modifications (shown in bold) of `ads.js` in the advanced HTML5\nsample available on our\n[download page](/interactive-media-ads/docs/sdks/html5/download). \n\n```javascript\nvar Ads = function(application, videoPlayer) {\n ...\n this.currentTime = 0;\n setInterval(this.updateCurrentTime, 1000);\n};\n\nAds.prototype.updateCurrentTime = function() {\n if (!this.videoPlayer_.contentPlayer.seeking) {\n this.currentTime = this.videoPlayer_.contentPlayer.currentTime;\n }\n};\n\nAds.prototype.onAdsManagerLoaded_ = function(adsManagerLoadedEvent) {\n this.application_.log('Ads loaded.');\n this.adsManager_ = adsManagerLoadedEvent.getAdsManager(this);\n this.processAdsManager_(this.adsManager_);\n};\n```\n\nKnown issues with mobile Safari\n\nThis method should work on every plaform except mobile Safari. On mobile\nSafari, the seeking property of the video tag is not properly implemented (it\nalways returns false). To get around that, you need to do your own check to\nsee if the user is seeking through the video. The sample code for this method\nfollows. Again, the bolded lines are modifications to existing code. \n\n```javascript\nvar Ads = function(application, videoPlayer) {\n ...\n this.currentTime = 0;\n setInterval(this.updateCurrentTime, 1000);\n this.seeking = false;\n this.seekCheckInterval = 1000;\n // You may need to adjust this value, depending on your platform\n this.seekThreshold = 100;\n this.previousTime = 0;\n setInterval(\n Application.bind(this, this.checkForSeeking),\n this.seekCheckInterval);\n};\n\nAds.prototype.updateCurrentTime = function() {\n if (!this.seeking) {\n this.currentTime = this.videoPlayer_.contentPlayer.currentTime;\n }\n};\n\nAds.prototype.checkForSeeking = function() {\n var currentTime = this.videoPlayer_.contentPlayer.currentTime;\n // How much time has passed since you last ran this method, in milliseconds\n var diff = (currentTime - this.previousTime) * 1000;\n // If that difference is greater than the time since you last ran this method,\n // plus the threshold, the user was seeking\n if (Math.abs(diff) \u003e this.interval + this.threshold) {\n this.seeking = true;\n } else {\n this.seeking = false;\n }\n // Grab the current video time again to make up for time spent in this method\n previousTime = this.videoPlayer_.contentPlayer.currentTime;\n};\n\nAds.prototype.onAdsManagerLoaded_ = function(adsManagerLoadedEvent) {\n this.application_.log('Ads loaded.');\n this.adsManager_ = adsManagerLoadedEvent.getAdsManager(this);\n this.processAdsManager_(this.adsManager_);\n};\n```\n\nWith these changes, the SDK is now using the currentTime property of your `Ads`\nobject to determine when to play ad breaks, not the `currentTime` property of the\ncontent video player."]]