Request FeedAds via the Web SDK

This guide requires an installed FeedAd SDK and therefore access to the feedad object. Read the installation guide if you have not initialized the SDK, yet.

Implementation

All asynchronous operations happening in the Web SDK are implemented as Promises and can be observed as such.

The ad request can be separated into five steps:

1. Initialize the SDK

You have to initialize the FeedAd SDK before requesting any ad.

feedad.init("your-web-client-token");

2. Request a placement

feedad.requestAd("your-placement-id")
      .then(function (adResponse) { 
      });

Placement ID?

You can choose placement IDs yourself. A placement ID should be named after the ad position inside your product. For example, if you want to display an ad inside a list of news articles, you could name it "ad-news-overview".
A placement ID may consist of lowercase a-z, 0-9, - and _. You do not have to manually create the placement IDs before using them. Just specify them within the code, and they will appear in the FeedAd admin panel after the first request. Learn more about Placement IDs and how they are grouped to play the same Creative

3. Add the ad to your page

The element holding the ad will be available through the adResponse.createAdContainer() property. You can add the element to your DOM to show the ad.

feedad.requestAd("your-placement-id")
      .then(function (adResponse) {
          // the ad element
          var adElement = adResponse.createAdContainer();
          // the ad should be added after the first paragraph
          var targetElement = document.body.querySelector("main > p:first-child");
          //insert the ad element
          targetElement.insertAdjacentElement("afterend", adElement);
      });

4. Listen for the ad completion

Once the ad element becomes visible, it will automatically start playing its creatives. When the FeedAd has finished playing all creatives, it will only show a blank view. To prevent that, you should listen for the ad response's promise to be fulfilled and remove the element in those callbacks.

feedad.requestAd("your-placement-id")
      .then(function (adResponse) {
          // the ad element
          var adElement = adResponse.createAdContainer();
          // the ad should be added after the first paragraph
          var targetElement = document.body.querySelector("main > p:first-child");
          //insert the ad element
          targetElement.insertAdjacentElement("afterend", adElement);

          // wait for the ad to finish and remove the ad element when playback is completed
          return adResponse.promise
                            .then(function () {
                                adElement.parentNode.removeChild(adElement);
                            });
      });

5. Listen for error events

Additionally, you can add listen for two possible error events:

  • The request fails.
    This can occur when there is no fill for the given placement or if there was an error during the ad request.
  • The playback fails.
    This can occur if the HTML5 video player throws an error during playback. For example, when the connection to the creative's source fails.

In both cases an error object with the same signature is returned:

  • error.errorCode: An error code number describing the type of the error:

    • feedad.FeedAdError.SDK (1):
      There was an error while communicating with FeedAd services.

    • feedad.FeedAdError.CONFIG (2):
      The error was caused by an invalid configuration of the FeedAd SDK.
      Please check the documentation on how to configure the SDK.

    • feedad.FeedAdError.PLAYBACK (3):
      An error was thrown while playing the media file.
      E.g. when the browser does not support the media file codecs.

    • feedad.FeedAdError.RESOURCE (4):
      An error was thrown because the URL of a media file is invalid.

    • feedad.FeedAdError.AD_NETWORK (5):
      The request of the VAST file of the ad network failed.

    • feedad.FeedAdError.CONNECTION (6):
      There is trouble with the internet connection.

    • feedad.FeedAdError.NO_FILL (7):
      There are no ads available.

    • feedad.FeedAdError.PARSER (8):
      There was an error while parsing the VAST file.

  • error.errorMessage: A string with details about the error.

You can listen for those errors using the catch callback on the promises.

// Full code example:
feedad.requestAd("your-placement-id")
      .then(function (adResponse) {
          // the ad element
          var adElement = adResponse.createAdContainer();
          // the ad should be added after the first paragraph
          var targetElement = document.body.querySelector("main > p:first-child");
          //insert the ad element
          targetElement.insertAdjacentElement("afterend", adElement);

          var removeAdElement = function () {
            adResponse.removeAdContainer(adElement);
            targetElement.removeChild(adElement);
          };

          // wait for the ad to finish and remove the ad element when playback completed
          return adResponse.promise
                            .then(removeAdElement)
                            .catch(function (e) {
                                console.log("error during playback", e);
                                removeAdElement();
                            });
      })
      .catch(function (e) {
          // if the ad request fails the reason will be logged.
          console.log("error requesting ad", e);
      });

Test your integration

Once you've setup all ad placements it is time to test the ad playback and error handling strategies.

Multiple Ad Containers

If you have a website with a long content, we recommend that you display the ad in multiple positions, while the user scrolls through your content. This will maximize your view through rate (VTR), which will result in a higher fill rate.

Since version 1.1.6 the Web SDK can render an ad in multiple visible containers at the same time. All you have to do is to create the ad container elements and include them inside your DOM.

See the multiple placements example of the example project for a demonstration on how to add multiple ad containers.

// Full code example:
feedad.requestAd("your-placement-id")
      .then(function (adResponse) {
          // Show the ad after each 10th paragraph.
          var contentContainer = document.body.querySelector("main");
          var targetElements = Array.prototype.slice.call(contentContainer.querySelectorAll("p:nth-child(10n)"));

          var adContainers = [];
          targetElements.forEach(function (target) {
              var container = adResponse.createAdContainer();
              adContainers.push(container);
              target.insertAdjacentElement("afterend", container);
          });

          // create a function that removes all previously added ad containers
          var cleanup = function () {
              adContainers.forEach(function (element) {
                  adResponse.removeAdContainer(element);
                  contentContainer.removeChild(element);
              })
          };

          // wait for the ad to finish and remove the ad containers when playback is completed
          return adResponse.promise.then(function () {
                                        console.log("ad playback completed");
                                        cleanup();
                                    })
                                    .catch(function (e) {
                                        console.log("error during playback", e);
                                        cleanup();
                                    });
      })
      .catch(function (e) {
          // if the ad request went wrong the reason will be logged.
          console.log("error requesting ad", e);
      });

Ad Request Options

You can provide additional options for the ad request:

feedad.requestAd("your-placement-id", {
    scaleMode: "parent_width",
    connectionType: "3g",
    showLoadingIndicator: true
});

The following keys and values are accepted by the options object:

Key Value
scaleMode
"parent_width" (default)
The player will have the same width as its parent element. The height will scale based on the creative's aspect ratio.
"parent_height"
The player will have the same height as its parent element. The width will scale based on the creative's aspect ratio.
"creative"
The ad player will size itself to the dimensions of the creative. You'll have to apply your own sizing.
connectionType "unknown" (default) | "wifi" | "2g" | "3g" | "4g"
Specifies the type of the connection so the ad server may filter out creatives with high bandwidth volume.
showLoadingIndicator true (default)
Specifies if a loading indicator should be visible while the ad is loading.

Update the Ad Request Options

Since version 1.2.5 of the FeedAd web SDK you can update the options while an ad is running. There are two possible ways to update the options on a running ad.

Using the Response Object

Update the options by calling the updateOptions(options) method on the ad response. The options parameter is an object literal with the same keys and values as in requestAd(...).

// Update options example:
feedad.requestAd("your-placement-id")
      .then(function (adResponse) {
          // ...

          // keep a reference to the response object and call updateOptions at any time
          adResponse.updateOptions({
            scaleMode: "creative",
            connectionType: "3g"
          });

          // ...
      });

Using a second Ad Request

If an ad is already running on your page, further calls to requestAd() with the same placement ID will just continue the ad playback. It will also return the same object it returned on the initial call.

However, calling this method with different options as in the first call will update the options of the currently running ad. This method is useful for Single-Page-Applications on which the an ad might be requested multiple times without a reference to the first ad response object.

// Initial ad request
feedad.requestAd("your-placement-id", {scaleMode: "parent_width", connectionType: "wifi"})
      .then(function (adResponse) {
          // ...
      });

// Another ad request somewhere else on the page will update the options
feedad.requestAd("your-placement-id", {scaleMode: "creative", connectionType: "2g"})
      .then(function (adResponse) {
          // ...
          // the response object is the same as the of the first call.
      });

Updating the connection type

If you update the connection type while an ad is running, the new connection type filter will be applied to the next video, after the current one completes playback. It is not possible to update the connection type for a running video.