Data Layer variables in ad slots

In this example, you will learn how to change ads inside Riddle with Data Layer. This is useful if you want to personalize the ad experiance for your customers.

Step 1

Go to Publish settings "Data Layer" and add a Data Layer Item "ad"

Step 2

You can use this Variable to send data to your ad iframe.

Variable content

Example Ad Iframe

<!DOCTYPE html>
<html>
  <head>
    <title>Data Layer Ads</title>
    <style>
      body {
        margin: 0;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }

      .example-ad {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100vh;
        background-color: #f0f0f0;
      }

      .ad-title {
        margin-bottom: 20px;
      }

      .ad-description {
        margin-bottom: 20px;
      }

      .ad-image {
        margin-bottom: 20px;
      }

      #data-layer-variable {
        font-weight: bold;
      }
    </style>
  </head>

  <body>
    <div class="example-ad">
      <div class="ad-title">
        <h1>Ad Title</h1>
      </div>
      <div class="ad-description">
        <p>Ad Description</p>
      </div>
      <div class="ad-image">
        <p>Data Layer Variable Content:</p>
        <p id="data-layer-variable"></p>
      </div>
    </div>
  </body>

  <script>
    function riddleEventListener(event) {
      if (
        !event.data.isRiddle2Event ||
        !event.data.category ||
        !event.data.category.startsWith("RiddleTrackEvent")
      ) {
        return;
      }

      // You can use the event data to modify the ad
    }

    function riddleDataLayerListener(event) {
      if (!event.data.isRiddleDataLayerEvent) {
        

        return;
      }

      var adVariableContent = event.data.riddleDataLayer.find(
          (f) => f.key === "ad"
        );

        if (adVariableContent) {
          document.getElementById("data-layer-variable").innerText =
            adVariableContent.value;
        }
    }

    function sendMessage() {
      window.parent.postMessage(
        {
          "ad-iframe-bottom": document.body.offsetHeight,
        },
        "*"
      );
    }

    (function () {
      sendMessage();

      // Listen for Riddle events
      window.addEventListener("message", riddleEventListener);
      window.addEventListener("message", riddleDataLayerListener);

      var height = document.body.offsetHeight;
      setInterval(function () {
        if (height != document.body.offsetHeight) {
          sendMessage();
          height = document.body.offsetHeight;
        }
      }, 100);
    })();
  </script>
</html>