If I write some JavaScript that runs in an <iframe> (which is dynamically created and added to the DOM with JavaScript, if that matters), is it isolated from the global namespace of its parent page, or are conflicts still possible?
I did some Googling and came across this page, but I can't really make sense of what he's doing here, or if it applies to exactly what I'm trying to determine/accomplish.
http://dean.edwards.name/weblog/2006/11/sandbox/
I'm creating a widget that will live on unknown host pages; it's a <script> that inserts an <iframe> on the page, then creates a document that loads some external scripts and inserts that document into the dynamically created <iframe>.
Basically, I just want to avoid conflicts with any global variables on the host page; I don't want any JavaScripts that I write or load in the <iframe> to conflict with anything on the host page.
If using an <iframe> doesn't automatically protect me, can anyone recommend an approach that will isolate any <script>s running in the <iframe>?
Thanks in advance for any guidance.
Because the namespace of each is separated, it should be fine. Consider the following
Host page JavaScript:
Foo = {};
Foo.bar = function(){ alert('hi!');}
Now the iframe JavaScript:
Foo = {};
Foo.bar = function(){ alert('yo!');}
For the iframe to talk to the parent, it would have to do something like this
window.parent.Foo.bar(); //Alerts 'hi!'
Foo.bar(); //Alerts 'yo!'
For the host page to see the frame, it would have to do this:
window.frames['nameOfFrame'].contentWindow.Foo.bar(); //Alerts 'yo!'
Foo.bar(); //Alerts 'hi!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With