如何检查浏览器是否支持WebAssembly? [英] How can I check if a browser supports WebAssembly?

查看:1696
本文介绍了如何检查浏览器是否支持WebAssembly?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有新的主要浏览器都支持WebAssembly,如何检查正在访问我网站的当前浏览器是否支持它?

With support for WebAssembly coming into all new major browsers, how can I check whether the current browser which is visiting my website supports it?

推荐答案

有几种方法可以检测WebAssembly的存在。基本的方法是检查 WebAssembly 是否在全局范围内为 object 类型,但在全局范围内在不同的JavaScript环境(主浏览器线程,工作程序,node.js)中进行操作是一件棘手的事情。

There are a few ways that you can detect the presence of WebAssembly. The basic one is to check whether WebAssembly if of type "object" in the global scope, but "global scope" is a tricky thing to get to in different JavaScript environments (main browser thread, worker, node.js).

这样做在技术上还不够,因为您可以拥有WebAssembly支持,但由于 CSP (实际上CSP不允许的是还没有标准化,请进行中此处)。

Doing so is also not technically sufficient because you could have WebAssembly support but be unable to actually compile or instantiate because of CSP (and exactly what CSP disallows isn't standardized yet, work ongoing here).

保守的检查如下:

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");

它执行以下操作:


  • 检查在当前范围内是否可以访问 WebAssembly 。如果不是全球性的,我们不在乎!

  • 查看它是否具有 .instantiate 函数,而实际上我们并没有在这里使用,但是在实际实例化时要使用它,因为它是异步的并且可以处理主线程上或关闭的大模块。

  • 尝试同步编译最小的模块(魔术)数字'\0','a','s','m',后跟编码为 uint32 ),看看是否从中获得了 WebAssembly.Module

  • 最后,尝试同步实例化该模块,并检查它是否为 WebAssembly.Instance

  • Check whether WebAssembly is accessible in the current scope. If it's not global we don't really care!
  • See whether it has the .instantiate function, which we don't actually use here but which you'd want to use when you actually instantiate because it's asynchronous and can handle large modules on the main thread or off.
  • Try to synchronously compile the smallest possible module (magic number '\0', 'a', 's', 'm', followed by version number 1 encoded as a uint32), and see if we get a WebAssembly.Module out of it.
  • Finally, try to synchronously instantiate that module, and check that it's a WebAssembly.Instance.

多少,但无论如何都可以工作:

This is a bit much but should work regardless of:


  • 代码在哪里运行(主线程,worker,node.js)。

  • CSP如何最终实现标准化。

这篇关于如何检查浏览器是否支持WebAssembly?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆