Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a wasm module locally?

I'm trying to make a simple, self-contained (only an .html file and a .wasm file) offline data visualization that uses JavaScript and WebAssembly. However, I'm having troubles loading the WASM module from a local file.

The first trouble is CORS. Trying to load any JS module with a relative or a file:// URL gets me security errors. On Firefox, I managed to disable local CORS, but that's icky and overly permissive. On Chrome, I'd need to start the browser with flags. Those are both non-starters from user perspective. Is there any way to load JS or WASM modules from a local file without running into CORS troubles?

Getting around CORS, the second trouble is that although Firefox is able to load JS modules, it fails with the WASM module: (my actual error message is in Japanese, but I think this is the English one) 'Loading failed for the ".wasm" with source'. No further info is shown. On Chrome, the error message is 'Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.', which suggests that both browsers might be suffering from not being able to guess the MIME type.

These both issues would be solved by setting up a HTTP server, but that entirely defeats the purpose of having a simple, self-contained file/files that need only the browser to run.

Is there a way to load and call WASM with only local files?

like image 833
GolDDranks Avatar asked Apr 06 '20 03:04

GolDDranks


People also ask

How do I load a Wasm file in HTML?

wasm : Create a new XMLHttpRequest() instance, and use its open() method to open a request, setting the request method to GET , and declaring the path to the file we want to fetch. The key part of this is to set the response type to 'arraybuffer' using the responseType property.


2 Answers

You can encode the wasm as base64 and then load it like this (no size limitation as far as I know - definitely works with 5Mb+)

Module.wasmBinaryFile="data:application/wasm;base64,AGFzbQEAAAABww...
like image 155
murkle Avatar answered Oct 17 '22 03:10

murkle


You can inline the Wasm binary as a Uint8Array, and instantiate it this way. It only works if it's small enough, though. I believe you get an error if the Wasm is more than 4KB.

// your Wasm file as a Uint8Array
const wasmSourceCode = new Uint8Array([0, 97, 115, 109 ...]);
const wasmModule = new WebAssembly.Module(wasmSourceCode );
const wasmInstance = new WebAssembly.Instance(wasmModule);
like image 32
GirkovArpa Avatar answered Oct 17 '22 01:10

GirkovArpa