December 4, 2015

How to know if a page loaded via iframe is within sandbox?

Layke’s Question:

I’m trying to detect if a page is loaded via a sandboxed iframe. Is this possible?

For example,we provide custom embeddable widgets and some people think they are being smart by sandboxing them in their iframe, but this breaks certain things.. such as window.top.location

Obviously, they could enable the features we need, but ideally, I should be able to just do something like:

"sandbox" in window.top

I have also tried doing

try {
    // do something that would not work if within sandbox
} catch(e) {

}

But this doesn’t work because it’s a browser security error, and not related to javascript.

JSFiddle actually sandbox their iframes to prevent window.top.location navigation, so this would be a good example to show you.
If you look at this example here:

http://jsfiddle.net/mwsb8geL/show/

You can see the error when you press the Instant Book Online button.

enter image description here

A project sandblaster can help you detect if you running being sandboxed.

Inside the iframe where you are testing if it is sandbox, open up your script tag and paste the contents of https://raw.githubusercontent.com/JamesMGreene/sandblaster/master/dist/sandblaster.js. This is due to the security issue.

After this, its as simple as the following.

var result = sandblaster.detect();
if(result.sandboxed === true) {
    //sandboxed
}

Here is a demo I made for another answer but shows that the solution works.

...

Please fill the form - I will response as fast as I can!