This post is just going to be a quick rundown on a neat trick I cobbled together today.
I build out a lot of services and such at the university which include embed-able widgets and players and such. Traditionally, we’ve used a SWF for all of these things and have used an object
/embed
type of HTML element structure to perform the embed. Over the past few years, we’ve been creating all new projects to utilize iframe
in place of this.
There are three primary reasons we are using iframe
to enabled embeds of this type:
- It allows us much greater control over the content. The page itself can include all sorts of JavaScript, Coldfusion, PHP, whatever and live on the server. If we need to adapt our logic for displaying items we just change it in one spot and it is updated everywhere. Infinitely flexible.
- Many video playback items have both a Flash Player and HTML
video
version. This allows logical switching between the two based upon platform and system capability. - It’s much easier for user to copy/paste a single line of code than the behemoth of
object
/embed
necessary in the older model.
So it comes time to adapt a specific widget (in this case – a pure SWF) into an iframe
embed. This poses a problem for this particular widget though. The SWF detects the current URL domain and based upon an internal list of allowed domains will either block the content or allow it.
With the old way of embedding, the SWF is embedded on the external site and the URL is easy to grab. With an iframe
– the SWF is ALWAYS embedded within the application domain. So it is ALWAYS allowed to show blocked content even when embedded upon domains which are not in the whitelist.
Oh my…
What’s the solution? Thankfully, iframe
has access to document.referrer
to detect the URL of the page it has been embedded within. Using some regex, we can whittle it down to a pure domain and then check this against an array of allowed domains. Problem solved!
var allowed = ["blackboard.du.edu", "ucolonline.com", "otl.du.edu"]; var iframe = (parent !== window); var url = null; if(iframe) { url = document.referrer; ref = url.match(/:\/\/(.[^/]+)/)[1]; for(i=0; i<=allowed.length; i++){ if(ref == allowed[i]){ summonSWF(); break; } } }
The summonSWF()
invocation is basically a call to a method which does some swfobject detection for embed along with some additional JavaScript which modified the DOM exposing a variety of outcomes for the user.
The overall logic of the page goes this this:
- Set up our whitelist
- Make sure we are being embedded
- Grab the full URL from the parent document
- Detect the raw domain from the full url
- Check this against our whitelist and respond accordingly.
The page will respond in one of three ways:
So is this completely secure? Foolproof? Of course not. However, for our purposes it does get the job done, nicely.
its tricky part of development but i can handle following your guides. thanks for this great help