use golang wasm in userscript(tampermonkey)

61 Views Asked by At
// ==UserScript==
// @name         test
// @namespace    http://tampermonkey.net/
// @version      v1
// @description  test
// @author       test
// @match        *://*/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=google.com
// @require      https://raw.githubusercontent.com/golang/go/master/misc/wasm/wasm_exec.js
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// ==/UserScript==

async function xFetch(url) {
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            onload: function (lol) {
                const headers = new Headers();
                lol.responseHeaders.trim().split(/[\r\n]+/).forEach(line => {
                    const parts = line.split(':');
                    headers.append(parts.shift().trim(), parts.join(':').trim());
                });
                const response = new Response(lol.responseText, {
                    status: lol.status,
                    statusText: lol.statusText,
                    headers: headers,
                });
                response.arrayBuffer = () => Promise.resolve(lol.response);
                resolve(response);
            },
            fetch: true,
            responseType: 'arraybuffer',
            onerror: reject,
        });
    });
}

(async function () {
    const go = new Go();
    WebAssembly.instantiateStreaming(await xFetch("https://****.glitch.me/wasm" /* its return wasm data with application/wasm content-type */ ), go.importObject).then(async (result) => {
        await go.run(result.instance);
    }).catch((err) => {
        console.error(err);
    });
})()

i trying to run golang wasm with tampermonkey, but got error (wasm work on web) i want solve that error.

use GM_xmlhttpRequest to bypass cross origin, replace response.arrayBuffer with () => Promise.resolve(lol.response) /lol.response = arrayBuffer/

if it works correctly, window.mywasmfunction function is set from the wasm

but got error CompileError: WebAssembly.instantiateStreaming(): length overflow while decoding section length @+13 how i can solve this error? this works on web using fetch.

0

There are 0 best solutions below