1

I have an iframe which loads local pages (proxy): I need the Javascript in these pages not to be executed (I am already executing it on the server, executing it again in the client leads to double execution, therefore bad).

I can achieve this by using the new "sandbox" argument.

The catch is that I need to be able to add events from the main window to the iframe contents. This does not seem to work.

I prepared an example using jsfiddle.

<iframe 
id='iframe1' 
sandbox='allow-top-navigation allow-same-origin allow-forms'
srcdoc='<html><head></head><body><div id="test">iframe1</div><script>document.body.style.backgroundColor="yellow"</script></body></html>'>
</iframe>

<iframe
id='iframe2'
srcdoc='<html><head></head><body><div id="test">iframe2</div><script>document.body.style.backgroundColor="yellow"</script></body></html>'>
</iframe>
$('iframe').load(function() {
    var id = this.id;

    //this works in both iframes
    $(this).contents().find("#test").html(id+" says gnek!");

    //I need this to work for iframe 1, too.
    $(this).contents().on("click", function(event) { 
        alert("clicked "+id);
    });
});

As you can see, frame1 is sandboxed and does not execute internal JS (background does not become yellow). However, I can change its contents using JS in the parent window.

Is there a way to add events, too? If not, what would be the best way to load a page into an iframe without letting it execute its javascript?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
fusio
  • 3,595
  • 6
  • 33
  • 47

1 Answers1

1

Attaching events to the content of a sandboxed iframe is the same as running the javascript from the iframe, hence it cannot be done.

I solved the problem of stopping JS execution by prepending in the <head> of the document the following:

<script>Function.prototype.call = Function.prototype.apply = function(){};</script>

EDIT: it seems like this is not enough. I finally decided to simply strip the <script>blocks from the document.

fusio
  • 3,595
  • 6
  • 33
  • 47
  • Such a clever solution! Nice. – mattsven Jul 04 '13 at 21:34
  • sadly, it is not enough it seems. have a look at this [jsfiddle](http://jsfiddle.net/NB2wX/). – fusio Jul 10 '13 at 00:07
  • Yikes, you're right. Not sure how I didn't notice that in my tests. If only there was another way to attach events. – mattsven Jul 10 '13 at 01:12
  • I am not sure why it does not work, actually. Care to explain? – fusio Jul 10 '13 at 10:45
  • 1
    I think I see why it's happening. Check out this Fiddle: http://jsfiddle.net/NB2wX/5/ As for what this means in regards to a solution...I'm not sure. There may not be one, other than figuring out how to strip out JS from the iframe's HTML. Which is tough. – mattsven Jul 10 '13 at 14:45
  • I'm wondering if there is any way to simply keep the iframe from accessing the topmost context... :/ No luck with trying to redefine window.top. – mattsven Jul 10 '13 at 14:59