javascript - 在 Chrome 沙箱中使用 WebAssembly

标签 javascript google-chrome-extension cors sandbox webassembly

我有一个 chrome 扩展,其中包含一个复杂的函数 comp_func(data),它通过执行许多按位运算占用大量 CPU。因此,我正在尝试使用 WebAssembly。 经过多次尝试,我得出的结论是,由于权限问题,我需要在沙箱内使用此函数。

现在我正在尝试关注this WebAssembly tutorialthis Sandbox example作为我的问题的“hello world”示例。

WebAssembly 文件包括:index.jsindex.wasm, 沙箱文件是:sandbox.htmlpage.js 是需要执行 comp_func(data) 的扩展代码,并使用 postMessage 作为与 通信的方式>sandbox.htmlbackground.html 是扩展程序的背景文件。

这是我到目前为止所拥有的:

ma​​nifest.json

   "sandbox": {
     "pages": ["sandbox.html"]
   },

背景.js

<script src="page.js"></script>
<iframe id="theFrame" src="sandbox.html" style="display: none;"></iframe>

sandbox.html

<html>
      <body>
        <script src="index.js"></script>
        <script>
        var result = _roll_dice(); //the function of the WebAssembly
        console.log('results! ', result);
        </script>
      </body>
    </html>

所以,现在扩展程序正在调用 sandbox.html,后者又加载 index.js,但随后我收到错误:

Failed to load chrome-extension://index.wasm: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

据我了解,index.js 正在调用 index.wasm 并且因为我位于沙箱内,CORS 存在问题> 权限。 有人知道这种情况下的解决方案是什么吗?

最佳答案

WebAssembly 模块通常通过 HTTP 从 JavaScript 加载,但是,还有其他方法可以将它们包含在代码中。例如,您可以对 WebAssembly 二进制文件进行 base64 编码,并将其作为字符串包含在内。或者,您可以使用构建工具(例如 rollup)来为您完成此操作:

https://github.com/rollup/rollup-plugin-wasm

这允许您引用 wasm 文件作为导入:

import wasm from './sample.wasm';

sample({ ...imports }).then(({ instance }) => {
  console.log(instance.exports.main())
})

但是,当使用 rollup 构建时,它将进行 Base64 编码和内联。

关于javascript - 在 Chrome 沙箱中使用 WebAssembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49491383/

相关文章:

javascript - JS正则表达式按行分割

javascript - react 和 NextJS : Module parse failed: Unexpected token

javascript - Base64 编码的图像在 IE 中不显示

go - 使用 Gin 测试 CORS 中间件

javascript - javascript在spring应用程序中访问属性文件中的值的最佳方式

javascript - 如何保持 Google Chrome 扩展程序弹出窗口打开?

javascript - 一起使用背景、内容和开发工具进行扩展

javascript - 内容安全策略错误,没有任何内联 JavaScript

javascript - 使用 prefixfree.js 和谷歌字体 api 时出现 CORS 和 'access control allow origin' 错误

amazon-web-services - 如何根据允许的来源列表设置 Access-Control-Allow-Origin header 的值?