如何从 WebAssembly 模块检测浏览器信息?

How to detect browser information from WebAssembly module?

如何从启动时通过 JavaScript 检测到的值(如当前 screen.availWidth)启动 C++ 变量(编译为 WebAssembly)?

此代码需要从 WebAssembly 模块启动,因此用户不能注入与真实值不同的值。

说明

您可以从 C++ 函数中 运行 编写 JavaScript 代码。这样的 JS 代码可以访问您在 Web 浏览器中 运行 时通常可以访问的所有对象。为此,我们将使用 EM_ASM_INT 宏来执行 JS 代码 returning 一个 int 值。

快速解决

我们将 JS 代码注入到 C++ 代码中 example.cppint main() 函数的使用确保代码在加载页面时自动执行,无需手动加载 WebAssembly 模块。但是,您也可以使用不同的函数,将其导出并在您的网页上执行。

#include <iostream>
#include <emscripten.h>

int main()
{
   int screen_width = EM_ASM_INT(
       return screen.availWidth;);
   std::cout << "Screen width=" << screen_width << std::endl;
}

我们用Emscripten compiler编译上面的example.cpp代码如下:

emcc example.cpp -o example.html

输出是一个网页,其中嵌入了 int main() 函数,其中包含 JS 代码(真的,开始)。 为了 运行 允许跨源资源共享 (CORS) 的代码,我们将使用 emrun 工具(我无法 运行 Firefox 上的示例,所以我使用了 Chrome 代替):

emrun --browser chrome example.html

评论

此方法适用于 return 类型标量值 int(使用 EM_ASM_INT)、double(使用 EM_ASM_DOUBLE)的 JS 代码,还有 char* 数组(使用 EM_ASM_INT 并仔细和手动内存管理,如图 here 所示)。