Pohodlná práce s formátem JSON v C++ díky knihovně nlohmann/json

22. 5. 2024
Doba čtení: 5 minut

Sdílet

Autor: Depositphotos
Tento článek pojednává o knihovně nlohmann/json, která přináší formát JSON do C++. Formát JSON je textový formát pro zápis dat. Díky tomu může sloužit pro přenos dat mezi komponentami bez ohledu na technologii.

JSON v C++

Programovací jazyk C++ nikdy nenabízel nativní podporu pro práci s formátem JSON. Bohužel práce s tímto formátem je relativně běžná – jedná se o jednoduchý formát použitelný například pro komunikaci mezi jednotlivými komponentami systému. Pokud tedy v nějakém projektu bylo nutné použít formát JSON, bylo k dispozici několik možností.

První z nich by byla napsat si vlastní parser, druhá by byla najít nějakou dobrou knihovnu pro práci s JSON a třetí možností by bylo nedělat projekt vůbec. Třetí možnost je naprosto nereálná – odmítáním projektů bychom umřeli hlady.

První možnost má velkou nevýhodu: napsat a hlavně otestovat nový kód vyžaduje docela velké množství času a nevím jak vy, ale já nikdy nezažil projekt, který by byl předfinancován a časově se stíhal. Zbývá tedy druhá možnost: najít knihovnu, která umí s formátem JSON pracovat. Pokud takovou knihovnu najdeme, musíme v rámci buildu správně nastavit cesty k hlavičkovým souborům a nastavit linkování.

Ti z nás, kteří píší kód použitelný na více operačních systémech, musejí ještě navíc řešit, zda je knihovna multiplatformní. Snadno použitelná knihovna na Linuxu může být peklo třeba ve Windows. Zde přichází na scénu knihovna nlohmann/json. Snadno se používá a je dodávána ve formě zdrojových (hlavičkových) souborů. To znamená, že pokud knihovnu chcete použít ve svém projektu, stačí pouze nastavit cestu.

Stručná historie nlohmann/json

První verze této knihovny byla vydána již roku 2015, od té doby byla neustále rozšiřována a zlepšována. Nejnovější release v době psaní článku je 3.7.3 z roku 2019. Autoři knihovny tvrdí, že cílem při vývoji nebylo vytvořit knihovnu s nejrychlejším zpracováním formátu JSON, ale knihovnu, která by zajistila co nejrychlejší vývoj aplikací (tedy její snadné použití).

Autoři se dále soustředili na: intuitivní syntaxi, triviální integraci do projektu (knihovna je dodána ve formě hlavičkových souborů, odpadají tedy jakékoliv problémy s linkováním) a testování. Co se testování týče, tak autoři tvrdí, že unit testy pokrývají 100% kódu včetně zpracování výjimek.

Načítání JSON

Knihovna nlohmann/json má vlastní datový typ nlohmann::json, ten umožňuje pohodlný přístup k jednotlivým položkám. V našem programu většinou JSON přijmeme ve formátu const char*, popřípadě std::string. Také se může stát, že je JSON uložen v souboru a my ho potřebujeme načíst. Načtení JSONu do datového typu nlohmann::json se provede velmi jednoduše, viz následující ukázky.

#include <fstream>
#include <nlohmann/json.hpp>
                                                                                                       f
std::ifstream f("config.txt");
nlohmann::json data = nlohmann::json::parse(f);

V ukázce vidíme includování knihoven pro práci se std::fstream a include knihovny nlohmann/json – toto je jediný include, který je potřeba do programu přidat. Je vidět, že slib snadného integrování do našeho kódu byl dodržen. Do funkce nlohmann::json::parse() můžeme přímo dodat i JSON ve formě const char*, viz ukázka:

nlohmann::json ex1 = nlohmann::json::parse(R"(
  {
    "pi": 3.141,
    "happy": true
  }
)");

Ono R před uvozovkami je literál značící, že jde o „Raw string“, pokud bychom R odstranili, museli bychom přidat escape sekvence pro speciální znaky – například horní uvozovku bychom museli zapsat jako  \".

Další možnost vytvoření je pomocí initializer-listu (featury dobře známé v C++). Zde malá poznámka: pokud inicializaci zapíšeme jako nlohmann::json ex4{"klic", "hodnota"}, nedostaneme ocekavany JSON {"klic" : "hodnota"}, ale JSON s polem hodnot, tedy ["klic", "hodnota"]  – toto je podle mě dost neintuitivní.

nlohmann::json ex3 = {
  {"jsem_happy", true},
  {"vek", 31.123},
};

Práce se komplikovanějším JSON

Předpokládejme, že chceme vytvořit následující JSON:

{
  "name": "Tomas Marny",
  "happy": true,
  "nothing_value": null,
  "age" : 31.123
  "favourite_numbers": {
    "lucky_number": 7,
    "unlucky_number" : 13
  },
  "list_of_calories": [458, 201, 433],
  "payments": {
    "currency": "BTC",
    "value": 0.11
  }
}

Možnost 1 – postupné vytváření:

Zde vytváříme JSON postupně. Do prázdného objektu typu nlohmann::json postupně přidáváme hodnoty pomocí operátoru[]. Použití tohoto operátoru je podobné kontejneru std::map: pokud hodnota existuje, je vrácena její hodnota a pokud ne, tak se hodnota vytvoří (defaultní je hodnota null). Vidíme, že lze přidávat hodnoty různých datových typů (lze použít i vlastní datový typ, pokud přetížíme správné operátory a funkce).

nlohman::json j; //vytvori prazdny objekt nlohmann::json

j["name"] = "Tomas Marny"; //std::string
j["happy"] = true; //pridani boolean
j["nothing"] = nullptr; //null hodnoty reprezentovany nullptr
j["age"] = 31.123; //desetinna hodnota (double)
j["favourite_numbers"]["lucky_number"] = 7; //int v objekt, ktery je v objektu poprve
j["favourite_numbers"]["unlucky_number"] = 13; //a podruhe
j["list_of_calories"] = { 458, 201, 433 }; //pridani pole hodnot
j["payments"] = { {"currency", "BTC"}, {"value", 0.11} }; //pridani dalsiho podobjektu pomoci initializer-list

Možnost 2 – vytvoření přes initializer-list:

Zde je vidět jak jednotlivé dvojice klíč-hodnota musejí být ve vlastních {}, tyto jednotlivé položky se poté přidají jako pole hodnot. Jak lze vidět v ukázce, je možné vytvořit i komplikovaný JSON s vnořenými strukturovanými objekty.

nlohmann::json j2 = {
  {"name", "Tomas Marny"},
  {"happy", true},
  {"nothing", nullptr},
  {"age", 31.123},
  {"favourite_numbers", {
    {"lucky_number", 7},
    {"unlucky_number", 13}
  }},
  {"list_of_calories", {458, 201, 433}},
  {"payments", {
    {"currency", "BTC"},
    {"value", 0.11}
  }}
};

Výpis a konverze do std::string

Pokud budeme s formátem JSON pracovat (například posílat jako data), budeme ho patrně potřebovat převést na std::string, to lze udělat metodou nlohmann::json::dump(), viz ukázka:

nlohmann::json ex = {
  {"pi", 3.141},
};

std::string jsonInString{ ex.dump() };

Popřípadě lze provést výpis s odsazením pomocí přidání parametru. Parametr reprezentuje odsazení jednotlivých vnořených položek.

std::cout << ex.dump(4) << std::endl;

Procházení formátu JSON

Knihovna nlohmann/json je vytvořena tak, aby její použití co nejvíce odpovídalo použití STL kontejneru (například std::vector). Pokud chceme projít prvky, nejjednodušší je použít iterátor, takto:

for (json::iterator it = j.begin(); it != j.end(); ++it) {
  std::cout << *it << '\n';
}

Pokud jste fanoušky C++17 a jeho vlastnosti „structured bindings“ lze zapsat procházení formátu JSON jako:

for (auto& [key, value] : jsonNew.items()) {
    std::cout << key << " : " << value << "\n";
}

Structured bindings je pohodlný způsob jak přiřadit několik hodnot najednou. Tato featura je již dlouho přítomná například v programovacím jazyce Python. V C++ se tato funkcionalita většinou obcházela použitím std::pair nebo std::tuple.

Hledání položky

Pokud potřebujeme otestovat, zda-li je konkrétní položka v JSON obsažena, musíme na to jít přes vyjímky a metodu nlohmann::json::at(). Datový typ nlohmann::json totiž stejně jako například std::map vytvoří referenci při použití operátoru[]. Pokud tedy máme JSON

zabbix_tip

 {"klic" : 123 }

v proměnné json1 a my zavoláme if (json1["neexistujici_klic"]) {...}, program uvnitř json1 vytvoří nový prvek s klíčem neexistujici_klic. Správný test na přítomnost s prvku s daným klíčem je v další ukázce:

try
{
    std::cout << j.at("neexistujici_klic") << std::endl;
}
catch (const nlohmann::json::exception& e)
{
    std::cout << e.what() << std::endl;
}

Licence

Pokud vás článek nalákal na použití knihovny nlohmann/json ve svém projektu a bojíte se její licence, tak mám dobrou zprávu. Knihovna je vydávána pod licencí MIT, můžeme si tedy s ní dělat téměř cokoliv, včetně použití v komerčním produktu.

Autor článku

Začínal na programovacích jazycích Pascal a PHP. Na ČVUT FIT se zamiloval do low-level C, které používá pro programování MCU. Programovací jazyk C++ považuje za dokonalý a rád by ho uměl pořádně.

'; document.getElementById('preroll-iframe').onload = function () { setupIframe(); } prerollContainer = document.getElementsByClassName('preroll-container-iframe')[0]; } function setupIframe() { prerollDocument = document.getElementById('preroll-iframe').contentWindow.document; let el = prerollDocument.createElement('style'); prerollDocument.head.appendChild(el); el.innerText = "#adContainer>div:nth-of-type(1),#adContainer>div:nth-of-type(1) > iframe { width: 99% !important;height: 99% !important;max-width: 100%;}#videoContent,body{ width:100vw;height:100vh}body{ font-family:'Helvetica Neue',Arial,sans-serif}#videoContent{ overflow:hidden;background:#000}#adMuteBtn{ width:35px;height:35px;border:0;background:0 0;display:none;position:absolute;fill:rgba(230,230,230,1);bottom:20px;right:25px}"; videoContent = prerollDocument.getElementById('contentElement'); videoContent.style.display = 'none'; videoContent.volume = 1; videoContent.muted = false; const playPromise = videoContent.play(); if (playPromise !== undefined) { playPromise.then(function () { console.log('PREROLL sound allowed'); // setUpIMA(true); videoContent.volume = 1; videoContent.muted = false; setUpIMA(); }).catch(function () { console.log('PREROLL sound forbidden'); videoContent.volume = 0; videoContent.muted = true; setUpIMA(); }); } } function setupDimensions() { prerollWidth = Math.min(iinfoPrerollPosition.offsetWidth, 480); prerollHeight = Math.min(iinfoPrerollPosition.offsetHeight, 320); } function setUpIMA() { google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true); google.ima.settings.setLocale('cs'); google.ima.settings.setNumRedirects(10); // Create the ad display container. createAdDisplayContainer(); // Create ads loader. adsLoader = new google.ima.AdsLoader(adDisplayContainer); // Listen and respond to ads loaded and error events. adsLoader.addEventListener( google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, onAdsManagerLoaded, false); adsLoader.addEventListener( google.ima.AdErrorEvent.Type.AD_ERROR, onAdError, false); // An event listener to tell the SDK that our content video // is completed so the SDK can play any post-roll ads. const contentEndedListener = function () { adsLoader.contentComplete(); }; videoContent.onended = contentEndedListener; // Request video ads. const adsRequest = new google.ima.AdsRequest(); adsRequest.adTagUrl = iinfoVastUrls[iinfoVastUrlIndex]; console.log('Preroll advert: ' + iinfoVastUrls[iinfoVastUrlIndex]); videoContent.muted = false; videoContent.volume = 1; // Specify the linear and nonlinear slot sizes. This helps the SDK to // select the correct creative if multiple are returned. // adsRequest.linearAdSlotWidth = prerollWidth; // adsRequest.linearAdSlotHeight = prerollHeight; adsRequest.nonLinearAdSlotWidth = 0; adsRequest.nonLinearAdSlotHeight = 0; adsLoader.requestAds(adsRequest); } function createAdDisplayContainer() { // We assume the adContainer is the DOM id of the element that will house // the ads. prerollDocument.getElementById('videoContent').style.display = 'none'; adDisplayContainer = new google.ima.AdDisplayContainer( prerollDocument.getElementById('adContainer'), videoContent); } function unmutePrerollAdvert() { adVolume = !adVolume; if (adVolume) { adsManager.setVolume(0.3); prerollDocument.getElementById('adMuteBtn').innerHTML = ''; } else { adsManager.setVolume(0); prerollDocument.getElementById('adMuteBtn').innerHTML = ''; } } function onAdsManagerLoaded(adsManagerLoadedEvent) { // Get the ads manager. const adsRenderingSettings = new google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; adsRenderingSettings.loadVideoTimeout = 12000; // videoContent should be set to the content video element. adsManager = adsManagerLoadedEvent.getAdsManager(videoContent, adsRenderingSettings); // Add listeners to the required events. adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, onContentResumeRequested); adsManager.addEventListener( google.ima.AdEvent.Type.ALL_ADS_COMPLETED, onAdEvent); // Listen to any additional events, if necessary. adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, onAdEvent); playAds(); } function playAds() { // Initialize the container. Must be done through a user action on mobile // devices. videoContent.load(); adDisplayContainer.initialize(); // setupDimensions(); try { // Initialize the ads manager. Ad rules playlist will start at this time. adsManager.init(1920, 1080, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will // start at this time; the call will be ignored for ad rules. adsManager.start(); // window.addEventListener('resize', function (event) { // if (adsManager) { // setupDimensions(); // adsManager.resize(prerollWidth, prerollHeight, google.ima.ViewMode.NORMAL); // } // }); } catch (adError) { // An error may be thrown if there was a problem with the VAST response. // videoContent.play(); } } function onAdEvent(adEvent) { const ad = adEvent.getAd(); console.log('Preroll event: ' + adEvent.type); switch (adEvent.type) { case google.ima.AdEvent.Type.LOADED: if (!ad.isLinear()) { videoContent.play(); } prerollDocument.getElementById('adContainer').style.width = '100%'; prerollDocument.getElementById('adContainer').style.maxWidth = '640px'; prerollDocument.getElementById('adContainer').style.height = '360px'; break; case google.ima.AdEvent.Type.STARTED: window.addEventListener('scroll', onActiveView); if (ad.isLinear()) { intervalTimer = setInterval( function () { // Example: const remainingTime = adsManager.getRemainingTime(); // adsManager.pause(); }, 300); // every 300ms } prerollDocument.getElementById('adMuteBtn').style.display = 'block'; break; case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: if (ad.isLinear()) { clearInterval(intervalTimer); } if (prerollLastError === 303) { playYtVideo(); } break; case google.ima.AdEvent.Type.COMPLETE: if (ad.isLinear()) { clearInterval(intervalTimer); } playYtVideo(); break; } } function onAdError(adErrorEvent) { console.log(adErrorEvent.getError()); prerollLastError = adErrorEvent.getError().getErrorCode(); if (!loadNext()) { playYtVideo(); } } function loadNext() { iinfoVastUrlIndex++; if (iinfoVastUrlIndex < iinfoVastUrls.length) { iinfoPrerollPosition.remove(); playPrerollAd(); } else { return false; } adVolume = 1; return true; } function onContentPauseRequested() { videoContent.pause(); } function onContentResumeRequested() { videoContent.play(); } function onActiveView() { if (prerollContainer) { const containerOffset = prerollContainer.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight/1 && containerOffset.bottom > 0.0) { if (prerollPaused) { adsManager.resume(); prerollPaused = false; } return true; } else { if (!prerollPaused) { adsManager.pause(); prerollPaused = true; } } } return false; } function playYtVideo() { iinfoPrerollPosition.remove(); youtubeIframe.style.display = 'block'; youtubeIframe.src += '&autoplay=1&mute=1'; } }
'; document.getElementById('outstream-iframe').onload = function () { setupIframe(); } replayScreen = document.getElementById('iinfoOutstreamReplay'); iinfoOutstreamPosition = document.getElementById('iinfoOutstreamPosition'); outstreamContainer = document.getElementsByClassName('outstream-container')[0]; setupReplayScreen(); } function setupIframe() { outstreamDocument = document.getElementById('outstream-iframe').contentWindow.document; let el = outstreamDocument.createElement('style'); outstreamDocument.head.appendChild(el); el.innerText = "#adContainer>div:nth-of-type(1),#adContainer>div:nth-of-type(1) > iframe { width: 99% !important;height: 99% !important;max-width: 100%;}#videoContent,body{ width:100vw;height:100vh}body{ font-family:'Helvetica Neue',Arial,sans-serif}#videoContent{ overflow:hidden;background:#000}#adMuteBtn{ width:35px;height:35px;border:0;background:0 0;display:none;position:absolute;fill:rgba(230,230,230,1);bottom:-5px;right:25px}"; videoContent = outstreamDocument.getElementById('contentElement'); videoContent.style.display = 'none'; videoContent.volume = 1; videoContent.muted = false; if ( location.href.indexOf('rejstriky.finance.cz') !== -1 || location.href.indexOf('finance-rejstrik') !== -1 || location.href.indexOf('firmy.euro.cz') !== -1 || location.href.indexOf('euro-rejstrik') !== -1 || location.href.indexOf('/rejstrik/') !== -1 || location.href.indexOf('/rejstrik-firem/') !== -1) { outstreamDirectPlayed = true; soundAllowed = true; iinfoVastUrlIndex = 0; } if (!outstreamDirectPlayed) { console.log('OUTSTREAM direct'); setUpIMA(true); } else { if (soundAllowed) { const playPromise = videoContent.play(); if (playPromise !== undefined) { playPromise.then(function () { console.log('OUTSTREAM sound allowed'); setUpIMA(false); }).catch(function () { console.log('OUTSTREAM sound forbidden'); renderBanner(); }); } } else { renderBanner(); } } } function getWrapper() { let articleWrapper = document.querySelector('.rs-outstream-placeholder'); // Outstream Placeholder from RedSys manipulation if (articleWrapper && articleWrapper.style.display !== 'block') { articleWrapper.innerHTML = ""; articleWrapper.style.display = 'block'; } // Don't render OutStream on homepages if (articleWrapper === null) { if (document.querySelector('body.p-index')) { return null; } } if (articleWrapper === null) { articleWrapper = document.getElementById('iinfo-outstream'); } if (articleWrapper === null) { articleWrapper = document.querySelector('.layout-main__content .detail__article p:nth-of-type(6)'); } if (articleWrapper === null) { // Euro, Autobible, Zdravi articleWrapper = document.querySelector('.o-article .o-article__text p:nth-of-type(6)'); } if (articleWrapper === null) { articleWrapper = document.getElementById('sidebar'); } if (!articleWrapper) { console.error("Outstream wrapper of article was not found."); } return articleWrapper; } function setupDimensions() { outstreamWidth = Math.min(iinfoOutstreamPosition.offsetWidth, 480); outstreamHeight = Math.min(iinfoOutstreamPosition.offsetHeight, 320); } /** * Sets up IMA ad display container, ads loader, and makes an ad request. */ function setUpIMA(direct) { google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true); google.ima.settings.setLocale('cs'); google.ima.settings.setNumRedirects(10); // Create the ad display container. createAdDisplayContainer(); // Create ads loader. adsLoader = new google.ima.AdsLoader(adDisplayContainer); // Listen and respond to ads loaded and error events. adsLoader.addEventListener( google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, onAdsManagerLoaded, false); adsLoader.addEventListener( google.ima.AdErrorEvent.Type.AD_ERROR, onAdError, false); // An event listener to tell the SDK that our content video // is completed so the SDK can play any post-roll ads. const contentEndedListener = function () { adsLoader.contentComplete(); }; videoContent.onended = contentEndedListener; // Request video ads. const adsRequest = new google.ima.AdsRequest(); if (direct) { adsRequest.adTagUrl = directVast; console.log('Outstream DIRECT CAMPAING advert: ' + directVast); videoContent.muted = true; videoContent.volume = 0; outstreamDirectPlayed = true; } else { adsRequest.adTagUrl = iinfoVastUrls[iinfoVastUrlIndex]; console.log('Outstream advert: ' + iinfoVastUrls[iinfoVastUrlIndex]); videoContent.muted = false; videoContent.volume = 1; } // Specify the linear and nonlinear slot sizes. This helps the SDK to // select the correct creative if multiple are returned. // adsRequest.linearAdSlotWidth = outstreamWidth; // adsRequest.linearAdSlotHeight = outstreamHeight; adsRequest.nonLinearAdSlotWidth = 0; adsRequest.nonLinearAdSlotHeight = 0; adsLoader.requestAds(adsRequest); } function setupReplayScreen() { replayScreen.addEventListener('click', function () { iinfoOutstreamPosition.remove(); iinfoVastUrlIndex = 0; outstreamInit(); }); } /** * Sets the 'adContainer' div as the IMA ad display container. */ function createAdDisplayContainer() { // We assume the adContainer is the DOM id of the element that will house // the ads. outstreamDocument.getElementById('videoContent').style.display = 'none'; adDisplayContainer = new google.ima.AdDisplayContainer( outstreamDocument.getElementById('adContainer'), videoContent); } function unmuteAdvert() { adVolume = !adVolume; if (adVolume) { adsManager.setVolume(0.3); outstreamDocument.getElementById('adMuteBtn').innerHTML = ''; } else { adsManager.setVolume(0); outstreamDocument.getElementById('adMuteBtn').innerHTML = ''; } } /** * Loads the video content and initializes IMA ad playback. */ function playAds() { // Initialize the container. Must be done through a user action on mobile // devices. videoContent.load(); adDisplayContainer.initialize(); // setupDimensions(); try { // Initialize the ads manager. Ad rules playlist will start at this time. adsManager.init(1920, 1080, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will // start at this time; the call will be ignored for ad rules. adsManager.start(); // window.addEventListener('resize', function (event) { // if (adsManager) { // setupDimensions(); // adsManager.resize(outstreamWidth, outstreamHeight, google.ima.ViewMode.NORMAL); // } // }); } catch (adError) { // An error may be thrown if there was a problem with the VAST response. // videoContent.play(); } } /** * Handles the ad manager loading and sets ad event listeners. * @param { !google.ima.AdsManagerLoadedEvent } adsManagerLoadedEvent */ function onAdsManagerLoaded(adsManagerLoadedEvent) { // Get the ads manager. const adsRenderingSettings = new google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; adsRenderingSettings.loadVideoTimeout = 12000; // videoContent should be set to the content video element. adsManager = adsManagerLoadedEvent.getAdsManager(videoContent, adsRenderingSettings); // Add listeners to the required events. adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, onContentResumeRequested); adsManager.addEventListener( google.ima.AdEvent.Type.ALL_ADS_COMPLETED, onAdEvent); // Listen to any additional events, if necessary. adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, onAdEvent); playAds(); } /** * Handles actions taken in response to ad events. * @param { !google.ima.AdEvent } adEvent */ function onAdEvent(adEvent) { // Retrieve the ad from the event. Some events (for example, // ALL_ADS_COMPLETED) don't have ad object associated. const ad = adEvent.getAd(); console.log('Outstream event: ' + adEvent.type); switch (adEvent.type) { case google.ima.AdEvent.Type.LOADED: // This is the first event sent for an ad - it is possible to // determine whether the ad is a video ad or an overlay. if (!ad.isLinear()) { // Position AdDisplayContainer correctly for overlay. // Use ad.width and ad.height. videoContent.play(); } outstreamDocument.getElementById('adContainer').style.width = '100%'; outstreamDocument.getElementById('adContainer').style.maxWidth = '640px'; outstreamDocument.getElementById('adContainer').style.height = '360px'; break; case google.ima.AdEvent.Type.STARTED: window.addEventListener('scroll', onActiveView); // This event indicates the ad has started - the video player // can adjust the UI, for example display a pause button and // remaining time. if (ad.isLinear()) { // For a linear ad, a timer can be started to poll for // the remaining time. intervalTimer = setInterval( function () { // Example: const remainingTime = adsManager.getRemainingTime(); // adsManager.pause(); }, 300); // every 300ms } outstreamDocument.getElementById('adMuteBtn').style.display = 'block'; break; case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: if (ad.isLinear()) { clearInterval(intervalTimer); } if (outstreamLastError === 303) { if (isBanner) { renderBanner(); } else { replayScreen.style.display = 'flex'; } } break; case google.ima.AdEvent.Type.COMPLETE: // This event indicates the ad has finished - the video player // can perform appropriate UI actions, such as removing the timer for // remaining time detection. if (ad.isLinear()) { clearInterval(intervalTimer); } if (isBanner) { renderBanner(); } else { replayScreen.style.display = 'flex'; } break; } } /** * Handles ad errors. * @param { !google.ima.AdErrorEvent } adErrorEvent */ function onAdError(adErrorEvent) { // Handle the error logging. console.log(adErrorEvent.getError()); outstreamLastError = adErrorEvent.getError().getErrorCode(); if (!loadNext()) { renderBanner(); } } function renderBanner() { if (isBanner) { console.log('Outstream: Render Banner'); iinfoOutstreamPosition.innerHTML = ""; iinfoOutstreamPosition.style.height = "330px"; iinfoOutstreamPosition.appendChild(bannerDiv); } else { console.log('Outstream: Banner is not set'); } } function loadNext() { iinfoVastUrlIndex++; if (iinfoVastUrlIndex < iinfoVastUrls.length) { iinfoOutstreamPosition.remove(); outstreamInit(); } else { return false; } adVolume = 1; return true; } /** * Pauses video content and sets up ad UI. */ function onContentPauseRequested() { videoContent.pause(); // This function is where you should setup UI for showing ads (for example, // display ad timer countdown, disable seeking and more.) // setupUIForAds(); } /** * Resumes video content and removes ad UI. */ function onContentResumeRequested() { videoContent.play(); // This function is where you should ensure that your UI is ready // to play content. It is the responsibility of the Publisher to // implement this function when necessary. // setupUIForContent(); } function onActiveView() { if (outstreamContainer) { const containerOffset = outstreamContainer.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight/1 && containerOffset.bottom > 0.0) { if (outstreamPaused) { adsManager.resume(); outstreamPaused = false; } return true; } else { if (!outstreamPaused) { adsManager.pause(); outstreamPaused = true; } } } return false; } let outstreamInitInterval; if (typeof cpexPackage !== "undefined") { outstreamInitInterval = setInterval(tryToInitializeOutstream, 100); } else { const wrapper = getWrapper(); if (wrapper) { let outstreamInitialized = false; window.addEventListener('scroll', () => { if (!outstreamInitialized) { const containerOffset = wrapper.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight / 1 && containerOffset.bottom > 0.0) { outstreamInit(); outstreamInitialized = true; } } }); } } function tryToInitializeOutstream() { const wrapper = getWrapper(); if (wrapper) { const containerOffset = wrapper.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight / 1 && containerOffset.bottom > 0.0) { if (cpexPackage.adserver.displayed) { clearInterval(outstreamInitInterval); outstreamInit(); } } } else { clearInterval(outstreamInitInterval); } } }
OSZAR »