Preventing Your Javascript From Loading In An IFrame

Aug. 26, 2008

4:58 am

I sure as donuts wish someone had written a post like this before I needed it. So even if you don't need it, file under "useful when someone's looking for an answer."

The Problem

Sometimes you just don't want the Javascript you've included on a page to load. I ran into one of these situations while working on a WordPress theme with a friend of mine. The theme in question uses Jan Sorgalla's ridiculously useful jCarousel plugin for jQuery on the homepage to load a list of text items that visitors can scroll through. You know: like a carousel.

But WordPress 2.6 has a new theme picker on the backend. When a site administrator is selecting a new theme, rather than switching your entire site to that theme immediately, the contents of your site are loaded in an iframe so you can see what it'll look like before committing. It's a gimmick of dubious usefulness, but that's beside the point. The short of it: the gimmick choked on our carousel. Errors galore. They even included the word "Aborting." Never good.

The Solution

The carousel is initiated by a chunk of script in the header of the page, so all we have to do is prevent that chunk from executing. Like this:

  1. if (window == window.top) {
  2. ...the chunklet of code...
  3. }

That's it. Even if you're a base JS novice like me, you know that window refers to the browser window – the global execution environment for all your code. It contains all the windows you see in your browser (and occasionally some you don't) including documents loaded in frames and iframes. Luckily window has a property called top that returns a reference to the document that contains all child documents. All we're saying here is "if the window where the code is loading is at the top, have at it." Otherwise, refrain. No more nasty error messages.

Oh, and be on the lookout for an announcement about this theme, likely some time in the next week. It is, as they say, super sweet.

Comments

November 27, 2009

6:46 am

Nice ... good use of the bit of information browsers provide.
Just a note, the non-strict comparison you use is correct, even for IE, so for purists out there (or jslinters) refrain from changing the above to:

window === window.top; // will not work for IE browsers

Diego Perini (#)

Whaddya think?