There are several ways to detect the presence of WebAssembly. The main one is to check WebAssemblyif there is a type "object"in the global scope, but the “global scope” is a difficult task to work in different JavaScript environments (main browser stream, workflow, node.js).
Doing this also is not technically sufficient, since you can have WebAssembly support, but you cannot actually compile or create an instance due to CSP (and it is clear that the CSP ban is not yet standardized).
A conservative check may be as follows:
const supported = (() => {
try {
if (typeof WebAssembly === "object"
&& typeof WebAssembly.instantiate === "function") {
const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
if (module instanceof WebAssembly.Module)
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
}
} catch (e) {
}
return false;
})();
console.log(supported ? "WebAssembly is supported" : "WebAssembly is not supported");
Run codeIt performs the following actions:
- Check if it is available
WebAssemblyin the current area. If it's not global, we don't care! - See if it has a function
.instantiatethat we don’t actually use here, but that you want to use when you actually create an instance, because it is asynchronous and can process large modules in the main thread or off. - (
'\0', 'a', 's', 'm', 1, uint32), , WebAssembly.Module. - , ,
WebAssembly.Instance.
, :