Introducing Runnable JavaScript, CSS, and HTML Code Snippets
On Stack Overflow and our other code-related sites, creating a minimal, complete, and verifiable example is the best way to get an answer to your question. We’ve always loved JSFiddle and sites like it because they let both askers and answerers reference runnable, working code that demonstrates their problem or solution.
Unfortunately, the use of these external sites introduces a few problems:
- If the link breaks, the post becomes worthless.
- If the code isn’t embedded in the page, visitors are forced to go elsewhere to get the full content of the question or answer.
- Also, because the code isn’t a part of our post Markdown, changes to it don’t show up in the revision history.
The community voiced similar concerns around external sites, which eventually led us to block posts that contain links to JSFiddle and similar sites without a corresponding code block. This is an unnecessary burden for both askers and answerers.
So we’ve created our own way to embed runnable JavaScript, CSS, and HTML code blocks right in the body of a post. As of today, we’re launching “Stack Snippets,” a fully integrated feature available on Stack Overflow and any other code-related Stack Exchange sites.
How Do Stack Snippets Work?
With Stack Snippets, a code block:
Can become a runnable code block:
The code will not run until you press the “Run code snippet” button:
How Do I Make A Stack Snippet?
Stack Snippets work for both questions and answers. In the Markdown editor window, there’s a new button that you can click to launch the Stack Snippets editor.
The editor appears and allows you to enter HTML, CSS, and JavaScript (or any combination of them):
Once you’ve got your code working, press “Insert into Post” at the bottom and you’re done! You can test your snippet, or load it back into the Snippets editor from right in the Preview screen:
When answering a post containing a snippet, you can easily include a modified version of the original in your answer – just click the “Copy snippet to answer” button.
Under the Hood
A great feature of Stack Snippets is that they are inserted as regular Markdown code blocks:
This makes them instantly backwards-compatible with our normal revision history and diffs, and also any API clients including our own mobile apps.
The runnable snippets behavior is triggered by a few new HTML comments that are not rendered by Markdown. You can even edit the code right from the Markdown editor and the snippet will still be runnable.
Are Stack Snippets Safe?
Yes, as much as the web in general is safe. You are not in any more danger than you are when browsing any site with JavaScript enabled. With that said, the snippets are running client code in your browser, and you should always exercise caution when running code contributed by another user.
We isolate snippets from our sites to block access to your private Stack Exchange data:
- We use HTML5 sandboxed iframes in order to prevent many forms of malicious attack.
- We render the Snippets 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 your logged-in session or cookies.
Like all other aspects of our site, Stack Snippets are ultimately governed by the community. Because users can still write code that creates annoying behaviors like infinite loops or pop-ups, we disable snippets on any post that is heavily downvoted (scoring less than -3 on Stack Overflow, -8 on Meta). If you see bad code that you think should be disabled, downvote the post. If you see code that is intended to be harmful (such as an attempt at phishing), you should flag it for moderator attention.
What About Other Languages?
Our initial release supports HTML, CSS, and JavaScript because questions on these topics use external code hosting sites the most frequently. These languages also run client-side in the user’s browser, making them self-contained and easy to support. Server-side languages are much more complicated and require significant infrastructure changes in order to properly implement. We don’t have any specific plans at this time to implement other languages, but it’s something we might consider in the future.
What About Sites Like JSFiddle?
You can still use sites like JSFiddle if you prefer them. JSFiddle and similar sites still have a bunch of features that we have not implemented yet. The normal rules for a link still apply: make sure you copy the relevant code into your question or answer so that it can be accessed if the external site is unavailable.
We decided to implement our own version instead of embedding a third-party site for the reasons mentioned earlier:
- There’s no need to copy-paste the code into the post. It’s all embedded in the post automatically, so revision history and diffs just work.
- There’s no need to visit another site to get your answer. The best experience is one where your question and answer(s) are complete and on the same page.
- Since we host it, we can guarantee performance and up-time. We have high standards when it comes to performance and up-time, and want to make sure that the ability to run a snippet is always available.
Give Stack Snippets A Try
We’re excited to see how the community uses Stack Snippets, and looking forward to your feedback:
- If you find bugs, or you’d like to give specific feedback on Stack Snippets, you can post on Meta Stack Exchange using the tag stack-snippets.
- If you just want to try it out, we’ve created a sandbox on Meta Stack Exchange.
- If you feel that a particular site should have Stack Snippets, post a feature-request on that site’s meta – if there’s support from the community there, we’ll enable them.
We’ve already started piloting it on Code Review and are seeing some neat results. Don’t hesitate to share interesting examples you come across – or create – here in the comments.
Have fun!
If you’d like to put your Javascript efforts to work, discover new opportunities in our Javascript job postings.
8 Comments
Its good but the snippets doesn’t work for questions like dom interactions with js. Check this question http://stackoverflow.com/questions/2920129/can-i-run-javascript-before-the-whole-page-is-loaded
You can just do this:
document.addEventListener(“DOMContentLoaded”, function(event) {
console.log(‘the DOM is available’);
});
Is there a way to avoid the Run Snippet button and just show? I’ve written a script to take the output from Terminal in OS X and produce a neat bordered list. You copy the terminal output to the clipboard, run my script and it pastes the snippet exactly as you do them back into the clipboard for pasting into post. Output doesn’t look right in a code block or raw so either there should be an output feature or rely on this sort of mechanism. Its just CSS and HTML.
This is great progress. Kudos to the StackOverflow team for finally implementing this!
What would be amazing is if y’all could support runnable code in other popular languages like C/C++, Java/Kotlin, Swift/ObjC, Ruby, etc.
I ran into an issue today where an API only accepts http requests on the free tier, but when you run the snippet the http is being converted to https, so the request fails. Any way to force http in snippets?
Another issue that I’ve run into with snippets with some services:
“Access to XMLHttpRequest at ‘https://ipapi.co/json/’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
Would it be possible to set a non-null `origin` in the request header?
About this ” We don’t have any specific plans at this time to implement other languages, but it’s something we might consider in the future.”
In the time since this article was written, Pyodide has provided a way to run Python in the browser from javascript using WebAssembly. The implementation is not perfect for all questions (not all packages work, tkinter and Flask wont work, threading is not supported, etc.), for many pure Python questions and answers it is a perfect fit. `numpy` works as well!
Pyodide doesn’t provide a great interface, but other packages like PyScript(https://pyscript.net/), PySnippet(https://github.com/pysnippet/pysnippet), and my project PyPrez(https://modularizer.github.io/pyprez/) can be used to provide interfaces which allow adding runnable python code to stack overflow questions and answers, using the HTML/JS/CSS tools which this article details .
There still is work needed to make runnable Python easy to use for the majority of questions, but it would be cool if the StackOverflow team was able to do so!
This feature addition makes a big difference in terms of verifying the code in stackoverflow itself. It makes web development with HTML, CSS, and JavaScript much easier.