Is it possible to use Web APIs with WebAssembly? If so, how? I'm more interested in the Navigator interface.
In your Visual Studio create a new app and select Blazor App Template for it. Next, on the Create a new Blazor app window select Blazor WebAssembly App Template, check below image. Your app will be created with basic Blazor Configuration and a few pages. Run the app in Visual studio and you can see it runs perfectly.
wasm binary. By itself, WebAssembly cannot currently directly access the DOM; it can only call JavaScript, passing in integer and floating point primitive data types. Thus, to access any Web API, WebAssembly needs to call out to JavaScript, which then makes the Web API call.
In one recent study, a developer discovered Wasm is faster than JavaScript across three desktop browsers on desktop computers and smartphones. Wasm is 1.15-1.67 times faster than JavaScript on Google Chrome on a desktop. Wasm is 1.95-11.71 times faster than JavaScript on Firefox on a desktop.
Yes, it is possible.
How to do call JavaScript APIs when using a WebAssembly toolchain is up to that specific toolchain. It's effectively a form of FFI: from C++ code it looks like you're calling an external function, but the toolchain bridges to the embedder (here, the browser's JavaScript). A few examples:
Toolchains such as Emscripten automatically generate an importObject
for WebAssembly.instantiate
(along with .html
and .js
files)/ Most of the internal WebAssembly details are therefore usually hidden (I document them below).
This design allows you to call any JavaScript code, not just JavaScript APIs. You can therefore call your own JavaScript code from WebAssembly. Toolchains simply make it easier to handle common sets of web APIs, sometimes in a cross-platform manner, e.g. SDL2 does audio, keyboard, mouse, joystick, and graphics.
WebAssembly's JavaScript API allows you to pass an importObject
to the WebAssembly.Instantiate
constructor and the WebAssembly.instantiate
function:
new Instance(moduleObject [, importObject]) Promise<{module:WebAssembly.Module, instance:WebAssembly.Instance}> instantiate(BufferSource bytes [, importObject])
The WebAssembly binary format contains an import section where you (through a compiler such as LLVM) declare the imports which it'll use. Each of these imported fields is looked up in the importObject
, and the functions can be invoked through WebAssembly's call
and call_indirect
opcode.
You can therefore call arbitrary JavaScript, which in turn can call any web API you want. In the future, WebAssembly may gain capabilities which allow the embedder expose APIs directly, in a browser embedding this could include the DOM, canvas, events, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With