JavaScript Ninja - How To Tell If You're Running Code From Within A SandBox'ed IFRAME

Posted at

How to know if you are running from within an iframe,
which has set to be sandbox'ed - without allowing scripts execution?

essentially you try and fail (an error will still be presented in the console)
to modify a close-related variable, which requires an injection/execute of
a script in the local-scope (self).

the following code, will give you an explicit
yes/no answer, for the script-sandbox state you are currently running from.

It is useful if you're running a JavaScript code, that
is originated from a Chrome-extension,
with "all_frames": true, set in the content_scripts.






function is_sandboxed(){
var is_sandbox;

self.is_sandbox = true;

var script = self.document.createElement("script");
script.appendChild(document.createTextNode("self.is_sandbox=false;"));
//script.onload, .onerror, .ontimeout will not work..
//wrapping the next line with try/catch will not work either, and still render an error... but you can't error handle it since error handling is in itself a forbidden usage.
self.document.documentElement.appendChild(script);

is_sandbox = true === self.is_sandbox; //true, explicit.
self.is_sandbox = undefined; //cleanup.

return is_sandbox;
}


if you want a test environment, you can use this plain
example in bin.eladkarako.com:


<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" dir="ltr" lang="en-US" language="English" charset="UTF-8" encoding="UTF-8">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<meta name="fragment" content="!"/>
<meta name="viewport" content="height=device-height,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width,minimal-ui"/>
</head>
<body>
<iframe src="about:blank" sandbox=""></iframe>
</body>
</html>


than right click the result (on the right), click "view source",
and switch to the newly-opened tab,
remove the "view-source:" prefix of the URL, and open up chrome's console,
select the scope, for the "about:blank" iframe, and try running the code above.

The code uses the self, to explicitly work with current iframe.