我有一个 chrome 扩展,其中包含一个复杂的函数 comp_func(data)
,它通过执行许多按位运算占用大量 CPU。因此,我正在尝试使用 WebAssembly。
经过多次尝试,我得出的结论是,由于权限问题,我需要在沙箱内使用此函数。
现在我正在尝试关注this WebAssembly tutorial和 this Sandbox example作为我的问题的“hello world”示例。
WebAssembly 文件包括:index.js
和 index.wasm
,
沙箱文件是:sandbox.html
,
page.js
是需要执行 comp_func(data)
的扩展代码,并使用 postMessage
作为与 通信的方式>sandbox.html
。
background.html
是扩展程序的背景文件。
这是我到目前为止所拥有的:
manifest.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/