HomeBook a Demo

Backfill unfilled GAM slots

Render an Inline AI question in Google Ad Manager slots that would otherwise go unfilled or serve a house ad, using a non-SafeFrame creative and a small bridge script on your page.

When one of your Google Ad Manager (GAM) slots has no paid demand, you can have it show an Inline AI question instead of a house ad or an empty box. GAM decides when to backfill; Inline AI renders the question (and, if your account has one configured, an ad under it) inside the space the slot already reserves, so nothing on the page shifts.

The setup has two parts:

  1. A bridge script on your pages. It knows which GAM slots may be backfilled and mounts the question into a slot when asked.
  2. A GAM line item and creative. When GAM serves it, the creative calls the bridge.

This guide assumes the Inline AI script is already on your pages in auto or hybrid mode (see Integration modes). The bridge does not call init(), so the placements configured in your dashboard keep loading as before.

How it works

  1. GAM runs its auction for a slot. Your backfill line item wins only when nothing pays more.
  2. The creative runs inside GAM's iframe and calls window.top.InlineGamBackfill.show(window).
  3. The bridge walks up from the creative's window to the slot element on your page and checks that the slot's ad unit path is on your allowlist.
  4. It adds an overlay container that fills the slot's reserved area and mounts a single-question placement into it through the command queue.
  5. When GAM requests that slot again (a refresh) or removes the creative, the bridge unmounts the question and removes the overlay. If the refresh fills with a paid ad, the ad shows as usual; if it backfills again, a fresh question is mounted.

The creative must run in a friendly (same-origin) iframe so it can reach your page. That is why the creative must not be served into a SafeFrame.

Step 1: Choose the slots

Pick the ad units you want to backfill and note their full ad unit paths (for example /1234567/Sidebar-Right-1).

  • Size. The question renders inside the slot's reserved area, at the slot's width. 300x250 and 300x600 work well. Smaller sizes, such as 320x50 or 728x90 leaderboards, leave too little room.
  • Width and ads. Some Inline AI ad formats need more than 300px of width. If your backfill slots are 300px wide, tell your Inline AI contact so they can tune the ad partners shown under the question.
  • Refreshing slots are supported. The bridge cleans up on every new request for the slot.

Step 2: Add the bridge script to your pages

Add this script to every page where the backfill line item can serve. It can run before or after the Inline AI script and before or after GPT: it only queues work on googletag.cmd and InlineAI.cmd. Replace the paths in allowedUnits with your own.

<script>
(function () {
  if (window.InlineGamBackfill) return;
 
  // Full GAM ad unit paths that may be backfilled.
  var allowedUnits = new Set([
    '/1234567/Sidebar-Right-1',
    '/1234567/Sidebar-Sticky-300x600'
  ]);
 
  var active = new Map();
  var counter = 0;
 
  window.InlineAI = window.InlineAI || {};
  window.InlineAI.cmd = window.InlineAI.cmd || [];
  window.googletag = window.googletag || { cmd: [] };
 
  function cleanup(slotId) {
    var state = active.get(slotId);
    if (!state) return;
 
    active.delete(slotId);
    state.observer.disconnect();
 
    if (state.placementId && state.sdk) {
      try {
        state.sdk.unmount(state.placementId);
      } catch (error) {
        console.error('Inline unmount failed:', error);
      }
    }
 
    state.container.remove();
 
    if (state.changedPosition) {
      state.adUnit.style.position = state.oldPosition;
    }
  }
 
  window.InlineGamBackfill = {
    show: function (creativeWindow) {
      var frame;
 
      // Find the creative's outermost iframe on this page.
      try {
        var current = creativeWindow;
        while (current !== window) {
          frame = current.frameElement;
          if (!frame) return;
          current = current.parent;
        }
      } catch (error) {
        console.error('Inline backfill requires a friendly iframe.', error);
        return;
      }
 
      if (!frame) return;
 
      window.googletag.cmd.push(function () {
        if (!frame.isConnected) return;
 
        var slot = window.googletag.pubads().getSlots().find(function (candidate) {
          if (!allowedUnits.has(candidate.getAdUnitPath())) return false;
          var element = document.getElementById(candidate.getSlotElementId());
          return element && element.contains(frame);
        });
 
        if (!slot) {
          console.error('Inline backfill: no eligible GAM slot found.');
          return;
        }
 
        var slotId = slot.getSlotElementId();
        var previous = active.get(slotId);
        if (previous && previous.frame === frame) return;
        cleanup(slotId);
 
        var adUnit = document.getElementById(slotId);
        var container = document.createElement('div');
        var question = document.createElement('div');
        var uniqueId = 'inline-gam-' + (++counter);
 
        container.id = uniqueId;
        question.id = uniqueId + '-question';
 
        // Cover the slot's reserved area instead of adding a new row.
        container.style.cssText =
          'position:absolute;inset:0;width:100%;box-sizing:border-box;z-index:1;';
 
        var oldPosition = adUnit.style.position;
        var changedPosition = window.getComputedStyle(adUnit).position === 'static';
        if (changedPosition) adUnit.style.position = 'relative';
 
        container.appendChild(question);
        adUnit.appendChild(container);
 
        var state = {
          frame: frame,
          adUnit: adUnit,
          container: container,
          oldPosition: oldPosition,
          changedPosition: changedPosition,
          sdk: null,
          placementId: null,
          observer: null
        };
 
        state.observer = new MutationObserver(function () {
          if (!frame.isConnected || !container.isConnected || !adUnit.contains(frame)) {
            cleanup(slotId);
          }
        });
 
        active.set(slotId, state);
        state.observer.observe(document.documentElement, { childList: true, subtree: true });
 
        window.InlineAI.cmd.push(function (sdk) {
          if (active.get(slotId) !== state) return;
          if (!frame.isConnected || !container.isConnected) {
            cleanup(slotId);
            return;
          }
 
          state.sdk = sdk;
          state.placementId = sdk.mount('single-question', {
            selector: '#' + uniqueId,
            anchorInjection: {
              tagName: 'div',
              attributeName: 'id',
              attributeValue: question.id
            },
            injectionStrategy: 'manual',
            injectionLimit: 1,
            location: 'append',
            width: '100%',
            maxWidth: '100%'
          });
 
          if (!state.placementId) cleanup(slotId);
        });
      });
    }
  };
 
  // A new request for a slot replaces whatever the bridge mounted there.
  window.googletag.cmd.push(function () {
    window.googletag.pubads().addEventListener('slotRequested', function (event) {
      cleanup(event.slot.getSlotElementId());
    });
  });
})();
</script>

If your site uses a framework script loader (for example Next.js <Script strategy="afterInteractive">), you can load the same code through it. The bridge only needs to be on the page before GAM renders the backfill creative.

Mount details

The bridge uses the fixed-slot pattern for the single question placement:

  • Each backfill gets its own container id (inline-gam-1, inline-gam-2, ...). mount() de-duplicates on the placement type and target element, so a shared container would make the second slot render nothing.
  • injectionStrategy: 'manual' with location: 'append' renders the question inside the container rather than after it.
  • mount() returns undefined when it cannot render. The bridge then removes its overlay and leaves the slot as GAM rendered it.

Step 3: Create the line item in GAM

  1. Go to Delivery > Orders > New order. Use an advertiser you reserve for this, for example "Inline AI Backfill".
  2. Add a new line item:
    • Type: Price priority, with a low CPM rate. Start low so the line item only wins impressions that would otherwise go unfilled or to house ads, then raise it once you know the fill rate. A House line item also works if you only want to replace house ads.
    • Expected creatives: the sizes of the slots from step 1 (for example 300x250 and 300x600).
    • Targeting: the ad units from step 1. The bridge ignores any ad unit that is not on allowedUnits, so keep the two lists in sync.
    • Leave frequency caps off.

Step 4: Add the creative

  1. In the line item, add a new creative of type Custom at each expected size.
  2. Untick "Serve into a SafeFrame". Inside a SafeFrame the creative cannot reach the bridge on your page.
  3. Paste this as the code snippet:
<script>
(function () {
  try {
    window.top.InlineGamBackfill.show(window);
  } catch (error) {
    console.error('Inline GAM backfill failed:', error);
  }
})();
</script>

Paste the snippet as plain text. Copying code through chat or document tools can turn straight quotes (') into curly quotes, which breaks the script without a visible error in GAM.

If your page forces SafeFrame for every slot (for example with googletag.pubads().setForceSafeFrame(true)), the creative setting is overridden. Exclude the backfill slots from that setting.

Step 5: Test

  1. In GAM, open the creative and use Preview in browser on one of your article pages. GAM adds google_preview parameters to the URL so the backfill line item serves on that load.
  2. Expected: the slot shows an Inline AI question at the slot's size, with nothing on the page shifting around it.
  3. Open DevTools. The console should show no Inline errors. window.InlineGamBackfill should be an object, and window.InlineAI.getPlacements() should list a single-question placement for each backfilled slot.
  4. If the slot refreshes, wait for the next refresh and confirm the question is replaced (or removed, when a paid ad wins).

On a page Inline AI has not processed yet there is no question to show, so the slot stays blank, the same as an unfilled slot. Inline AI processes a page the first time it loads with the script, usually within a few minutes.

Troubleshooting

Console messageCauseFix
Inline backfill requires a friendly iframe.The creative is in a SafeFrame or a cross-origin frame.Untick Serve into a SafeFrame on the creative and check the page does not force SafeFrame.
Inline backfill: no eligible GAM slot found.The slot's ad unit path is not in allowedUnits, or the path differs (for example a missing network code).Copy the exact path from googletag.pubads().getSlots().map(s => s.getAdUnitPath()).
Inline GAM backfill failed: ... InlineGamBackfill is undefinedThe bridge script is not on this page, or it loaded after the creative rendered.Add the bridge to every page the line item targets, early in the page.
No message, nothing rendersThe page has no questions yet, or the Inline AI script is not on the page.Load the page once without preview and retry after a few minutes. Check that window.InlineAI.getPlacements exists.

Go-live checklist

  • The bridge script is on every page the line item can serve on.
  • allowedUnits matches the line item's ad unit targeting.
  • The creative is Custom with Serve into a SafeFrame unticked.
  • A GAM preview shows the question inside the slot with no layout shift.
  • You have told your Inline AI contact which slots and sizes you are backfilling, so they can confirm delivery and tune ads for the slot width.