This very simple and minimal tutorial documents in a few easy steps how to play with WebAssembly (WASM) and get first results within minutes.
While the code below is mostly useless, it will show, how to call the alert
function from within a WASM file and thus demonstrate how to import and export DOM objects.
Of course, this exercise has no real use. It is just meant to show, that getting started with WASM isn't hard. And there is no need for a complex build-chain, tons of tools or a dedicated VMs. Just use a browser, one online tool and that's it.
To execute the code shown below, we need a very modern browser. WASM likely needs to be enabled via configuration flag. We tested on Chrome Version 52.0.2741.0 Canary and activated chrome://flags/#enable-webassembly
. Same for Firefox 49.0a1 with javascript.options.wasm: true
.
We need nothing else but the browser, one HTML file and a WASM file. We can use the amazing tool linked below to generate the WASM file for us - from WAST. No complex build chain needed:
Create an HTML file using the following source code:
<script>
/* An XHR fetching the WASM file as ArrayBuffer */
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = ready;
xhr.open('GET', 'test.wasm');
xhr.send(null);
/* Execute once the file was fetched */
function ready() {
var info = {
foo: {bar: alert} // "import" the alert method
};
var a = Wasm.instantiateModule(
new Uint8Array(xhr.response), info
).exports;
a.f(); // execute the f method, that is foo.bar()
}
</script>
Now, let's create some WAST code to feed to the tool linked above and generate a WASM for for us (test.wasm
, as referenced in the HTML):
(module ;; start the module
(import "foo" "bar") ;; import foo.bar
(func $bar (call_import 0 )) ;; map bar()
(export "f" 0) ;; export bar()
)
Click "Download", grab the resulting WASM file, place it in the same folder as your HTML file, open the HTML in Chrome or any WASM-compatible browser of choice, see the alert pop. Done :) Why? Because why not!
<script> WebAssembly.instantiate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 8, 2, 96, 1, 127, 0, 96, 0, 0, 2, 8, 1, 2, 106, 115, 1, 95, 0, 0, 3, 2, 1, 1, 8, 1, 1, 10, 9, 1, 7, 0, 65, 185, 10, 16, 0, 11]), { js: { _: alert } }); </script>