tl; dr Is it possible to safely execute untrusted scripts in an iframe?
Background History:
I am trying to make secure JSONP requests . Many older browsers do not support web workers, which means that the current solution I came up with is not optimal.
I decided that I could create an <iframe> and load the script inside it. This script would execute a JSONP request (by creating a script tag) that posted the message on the main page. On the main page, you will get a message, call back and destroy the iframe. I managed to do such things .
function jsonp(url, data, callback) { var iframe = document.createElement("iframe"); iframe.style.display = "none"; document.body.appendChild(iframe); var iframedoc = iframe.contentDocument || iframe.contentWindow.document; sc = document.createElement("script"); sc.textContent = "(function(p){ cb = function(result){p.postMessage(result,'http://fiddle.jshell.net');};})(parent);"; //sc.textContent += "alert(cb)"; iframedoc.body.appendChild(sc); var jr = document.createElement("script"); var getParams = ""; // serialize the GET parameters for (var i in data) { getParams += "&" + i + "=" + data[i]; } jr.src = url + "?callback=cb" + getParams; iframedoc.body.appendChild(jr); window.onmessage = function (e) { callback(e.data); document.body.removeChild(iframe); } } jsonp("http://jsfiddle.net/echo/jsonp/", { foo: "bar" }, function (result) { alert("Result: " + JSON.stringify(result)); });
The problem is that since the frames are in the same domain, the injected script still has access to the external area via .top or .parent and the like.
Is there a way to create an iframe that cannot access data in the parent scope?
I want to create an iframe where scripts added through script tags cannot access the variables in the parent window (and the DOM). I tried things like top=parent=null , but I'm really not sure if this is enough, there may be other workarounds. I tried to run for ... in loop, but my function stopped working, and I could not figure out why.
NOTE.
I know optimally. WebWorkers is the best sandbox. I know that JSONP is a “bad” technique (I even had some random guy to say that he would never use it today). I am trying to create a safe scripting environment where you must execute JSONP requests.
source share