Monday, November 20th, 2006

Sandboxing JavaScript with iframes

Category: JavaScript, Tip

Dean Edwards is hacking away again. This time he created a sandbox object that allows him to eval code outside of the context of window. His scenario was with templating:

javascript

  1. // create an <iframe>
  2. var iframe = document.createElement("iframe");
  3. iframe.style.display = "none";
  4. document.body.appendChild(iframe);
  5.  
  6. // write a script into the </iframe><iframe> and create the sandbox
  7. frames[frames.length - 1].document.write(
  8.     "<script>"+
  9.     "var MSIE/*@cc_on =1@*/;"+ // sniff
  10.     "parent.sandbox=MSIE?this:{eval:function(s){return eval(s)}}"+
  11.     "< \/script>"
  12. );

He then realized that he could use this knowledge for more good, allowing us to finally subclass Array correctly (and not break .length).

Nicely done sir.

Posted by Dion Almaer at 6:21 am
7 Comments

++++-
4 rating from 26 votes

7 Comments »

Comments feed TrackBack URI

well done Dean !!! … but I hope You’re not creating an eval based JavaScript template engine :D

Comment by Andrea Giammarchi — November 20, 2006

WOW great IDEA!!!!!

Comment by Mario — November 20, 2006

most useful scripts this year :P

Comment by Cheng Guangnan — November 20, 2006

Weird, I can’t get either of the articles pointed to here on Dean’s site to display, either in Firefox or in IE. I’ve seen this happen before on my own sites, where the css sheets aren’t being served properly by the server, don’t know if that’s what’s happening here or not.

Comment by Mike Ritchie — November 20, 2006

Deans Site ishosted from a PC in his kitchen. Come back in 30 min. or so. he prol got tons of hits when the story broke.

Comment by Mario — November 20, 2006

[…] Ajaxian ” Tip Scott Guthrie has written up a tip for Enabling Back/Forward-Button Support for … JavaScript, Ruby, Prototype, RichTextWidget, Tip, Safari, Scriptaculous … […]

Pingback by Your Online Marketing At The >>Next>> Level » Blog Archive » Applied Physics Research and Product (Online Marketing) Development - The Industrial Physicist — November 23, 2006

you can also use new ActiveXObject(”htmlfile”); in IE instead of an iframe (I know the popup method has been discuss for IE too). A link discussing the ActiveXObject(”htmlfile”) can be found here: http://alex.dojotoolkit.org/?p=538

Comment by Mario — November 30, 2006

Leave a comment

You must be logged in to post a comment.