using WebAssembly in chrome extension

前端 未结 1 897
感情败类
感情败类 2021-01-30 17:56

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

相关标签:
1条回答
  • 2021-01-30 18:13

    I've been fiddling with WebAssembly recently, and found a way to make it work. Here are the script files:

    main.js

    chrome.browserAction.onClicked.addListener(function(tab) {
     chrome.tabs.executeScript(null, {file: "content_script.js"});
    });
    

    content_script.js

      var importObject = { imports: { imported_func: arg => console.log(arg) } };
      url = 'data:application/wasm;base64,' + "AGFzbQEAAAABCAJgAX8AYAAAAhkBB2ltcG9ydHMNaW1wb3J0ZWRfZnVuYwAAAwIBAQcRAQ1leHBvcnRlZF9mdW5jAAEKCAEGAEEqEAAL";
      WebAssembly.instantiateStreaming(fetch(url), importObject)
      .then(obj => obj.instance.exports.exported_func());
    

    The data URL belongs to the common tutorial wasm sample (simple.wasm), which writes 42 on the console.


    PS. If it seems like cheating or bad practice to you, this content_script.js also works:
    var importObject = {
       imports: {
        imported_func: function(arg) {
        console.log(arg);
        }
       }
     };
    
    var response = null;
    var bytes = null;
    var results = null;
    
    
    var wasmPath = chrome.runtime.getURL("simple.wasm");
    fetch(wasmPath).then(response =>
        response.arrayBuffer()
        ).then(bytes =>
           WebAssembly.instantiate(bytes, importObject)
            ).then(results => {
            results.instance.exports.exported_func();
      });
    

    Only if you include the code files in the web_accessible_resources section in manifest.json, though:

        ...
        "web_accessible_resources": [
         "content_script.js",
         "main.js",
         "simple.wasm"
        ],
        ...
    

    Github: https://github.com/inflatablegrade/Extension-with-WASM

    0 讨论(0)
提交回复
热议问题