Como processar várias solicitações de anúncios com o UserContext

Most uses of the IMA SDK only require managing a single ad request at a time. However some edge case implementations, such as preloading ad data before the user selects a video, may require making multiple concurrent requests. Since ad requests are made asynchronously, ensuring the proper ad manager is associated with the correct context can seem to be a daunting task.

To simplify the process of differentiating multiple ad managers, the IMA SDK for HTML5 allows publishers to pass in any value or object to the UserContext field of any ad request. This value or object can then be retrieved in the AdsManagerLoadedEvent handler, by using the method getUserRequestContext().

Example

...
adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded,
      false);
adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdsManagerError,
      false);
const contextA = {id: "Request A", element: videoElementA};
const contextB = {id: "Request B", element: videoElementB}
adsLoader.requestAds(adsRequestA, contextA);
adsLoader.requestAds(adsRequestB, contextB);
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  const context = adsManagerLoadedEvent.getUserRequestContext();
  adsManager = adsManagerLoadedEvent.getAdsManager(context.element);
  console.log("Successfully loaded ID: " + context.id);
}

function onAdsManagerError(adsManagerErrorEvent) {
  const context = adsManagerErrorEvent.getUserRequestContext();
  console.log("Error with AdRequest ID: " + context.id);
}
...