I have a chrome extension that includes a complicated function comp_func(data)
which takes a lot of CPU by performing many bitwise operations. Because of that, I'm trying to use WebAssembly.
I've tried to follow several tutorials, for example this one and this one.
The first link says:
fetch('simple.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
results.instance.exports.exported_func();
});
but I get an error:
Uncaught (in promise) TypeError: WebAssembly Instantiation: Import #0 module="env" error: module is not an object or function
I've tried a lot to use this approach, but it didn't work. I can't understand how to use WebAssembly that is loaded from the .wasm
file.
So I've tried an easier approach: The second link says to put this line in the html file:
<script src="index.js"></script>
and then just use the exported function:
var result = _roll_dice();
BUT, I'm in an extension so I only have a background.html
file.
So I'm looking for a way to access the Module which was loaded in the background file.
And things get complicated, because the function comp_func(data)
is called from a Worker.
This is what I've tried so far:
If I call chrome.extension.getBackgroundPage()
I can access the Module
but I can't send it to the Worker:
Failed to execute 'postMessage' on 'Worker': # could not be cloned.
And if I try to stringify
it first:
Uncaught TypeError: Converting circular structure to JSON
(I tried to un-circular it, didn't work...)
And I can't call chrome.extension.getBackgroundPage()
from the Worker because I can't access chrome API from there.
So my questions are:
- Did someone try to load
.wasm
file in chrome extension and succeed? The second approach (loading thejs
file) sounds simpler but if you have a working example for this approach it would be great.
or 2. How to access the Module that has been loaded in background.html
(from the second example)?
or 3. How to pass the functions that I needed from the js file to the Worker (via postMessage
)?
To summarize, did someone try to use WebAssembly in a chrome extension and survive to tell?
EDIT: I eventually left the approach of WebAssembly. I also posted this question at bugs-chromium, and after few month got an answer. Not sure if this is really working, but maybe this, along with the marked answer, will help someone.