Unfortunately, iFrames still exist. They are used to embed content from one page into another. Frames are horrible, nasty things, very often riddled with cross-domain problems, performance issues, responsive design obstructions and other crap from the nether pits of hell. Regardless, if you’re stuck with an iFrame which also collects data to your Google Analytics property, for example, you probably want to prevent at least the first Page View from firing, since otherwise you’ll be double-counting Page Views: once on the main page and once in the iFrame. In this tip, I’ll show you how to prevent a Tag from firing if it’s executed in a document that is in an iFrame.

Tip 31: Prevent Tag from firing in an iFrame

For easy copying, here’s the code:

function() {
  try {
    return window.top !== window.self;
  } catch(e) {
    return false;
  }
}

As you can see, it’s a simple solution. The Custom JavaScript Variable simply checks if the window object on the page is different than the window object on the outermost frame. This script thus returns true if there is a difference, meaning the page is not loaded in the outermost frame (and is thus in an iFrame), and false if there is no difference, meaning the page is the “main” document. The Trigger would thus look like this:

Add this Trigger as an Exception to a Tag which fires upon the Page View Event, and you will effectively block the iFrame from sending the Page View.

If you want to create a “global” Exception, which blocks all Tags from firing when in an iFrame, use the Custom Event Trigger:

Sometimes you only want to block the first Page View in the iFrame, but then allow the user to navigate from page to page in the frame, sending Page Views for subsequent pages. In that case, you need a bit more creativity, and you’ll need to check for the Referrer, blocking the Tag if the Referrer is the “main” document:

This solution should work cross-domain, since simply checking for the window object does not violate same-origin policy. There have been scattered reports about unreliability in some earlier versions of Internet Explorer (surprise, surprise), so it’s good to have a fallback if the script fails, which is why it sends the false upon an error.