The runnable snippets on Stack Overflow for JavaScript, HTML and CSS are a very convenient feature. I was wondering how is it implemented.
From what I could find on this link, Stack Overflow implements it using HTML5 sandboxed iframes in order to prevent many forms of malicious attack. The Snippets are rendered on an external domain (stacksnippets.net) in order to ensure that the same-origin policy is not in effect and to keep the snippets from accessing logged-in session or cookies.
However, I could not find a more detailed explanation of how it works. I played around with the Chrome Dev Tools and found out:
- The output is displayed in an iframe with the following sandbox attribute
<iframe sandbox="allow-forms allow-modals allow-scripts">
- The origin of the iframe is null
- A POST request is sent to https://stacksnippets.net/js. The origin of this request is https://stackoverflow.com and the request form data is
js: foo css: bar html: baz
. - The response is a complete HTML doc with a script tag
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
- Next is a GET request to stacksnippets.net to get /scripts/snippet-javascript-console.min.js. The origin for this request could not be found on Chrome Dev Tools. The referrer was https://stacksnippets.net/ itself.
Can anyone explain how this whole thing happens? Where does the code live, how does it not interact with the parent cookies, where do the scripts run, how it prevents XSS attacks? How does it work even when iframe has null origin?
And how does Stack Overflow ensure that the scripts are executed securely?
<style>
tag in the head and the html of course is in the body also. The code lives in the snippet and gets posted every time you hit Run then inserted into the iframe page templateconsole: <true/ false>
andbabel: <true/ false>
, as well as the 3 code parameters you mention.