簡體   English   中英

從 JavaScript 調用函數

[英]Calling a function from JavaScript

試圖在 go 中理解 wasm,所以我寫了以下內容:

  1. 操作 DOM
  2. 調用JS函數
  3. 定義一個可以被JS調用的函數

前 2 個步驟很好,但最后一個沒有按預期工作,因為我得到了function undefined的 JavaScript 錯誤function undefined ,我的代碼在下面,我遇到的問題出在函數sub

package main

import (
    "syscall/js"
)

// func sub(a, b float64) float64

func sub(this js.Value, inputs []js.Value) interface{} {
    return inputs[0].Float() - inputs[1].Float()
}

func main() {
    c := make(chan int) // channel to keep the wasm running, it is not a library as in rust/c/c++, so we need to keep the binary running
    js.Global().Set("sub", js.FuncOf(sub))
    alert := js.Global().Get("alert")
    alert.Invoke("Hi")
    println("Hello wasm")

    num := js.Global().Call("add", 3, 4)
    println(num.Int())

    document := js.Global().Get("document")
    h1 := document.Call("createElement", "h1")
    h1.Set("innerText", "This is H1")
    document.Get("body").Call("appendChild", h1)

    <-c // pause the execution so that the resources we create for JS keep available
}

將其編譯為 wasm 為:

GOOS=js GOARCH=wasm go build -o main.wasm wasm.go

wasm_exec.js文件復制到與以下相同的工作文件夾:

cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .

我的 HTML 文件是:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>WASM</title>
    <script src="http://localhost:8080/www/lib.js"></script>
    <!-- WASM -->
    <script src="http://localhost:8080/www/wasm_exec.js"></script>
    <script src="http://localhost:8080/www/loadWasm.js"></script>
</head>
<body>
</body>
<script>
   console.log(sub(5,3));
</script>
</html>

lib.js是:

function add(a, b){
    return a + b;
}

loadWasm.js是:

async function init(){
    const go = new Go();
    const result = await WebAssembly.instantiateStreaming(
        fetch("http://localhost:8080/www/main.wasm"),
        go.importObject
    );
    go.run(result.instance);
}
init();

服務器代碼是:

package main

import (
    "fmt"
    "html/template"
    "net/http"
)

func wasmHandler() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        tmpl := template.Must(template.ParseFiles("www/home.html"))

        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        err := tmpl.Execute(w, nil)
        if err != nil {
            fmt.Println(err)
        }
    })
}

func main() {
    fs := http.StripPrefix("/www/", http.FileServer(http.Dir("./www")))
    http.Handle("/www/", fs)

    http.Handle("/home", wasmHandler())
    http.ListenAndServe(":8080", nil)

}

我得到的輸出是:

在此處輸入圖片說明

更新

我嘗試使用下面的 TinyGO 示例,但遇到了幾乎相同的問題:

//wasm.go

package main

// This calls a JS function from Go.
func main() {
    println("adding two numbers:", add(2, 3)) // expecting 5
}

// module from JavaScript.
func add(x, y int) int

//export multiply
func multiply(x, y int) int {
    return x * y
}

編譯為:

tinygo build -o main2.wasm -target wasm -no-debug
cp "$(tinygo env TINYGOROOT)/targets/wasm_exec.js" .

server.go為:

package main

import (
    "log"
    "net/http"
    "strings"
)

const dir = "./www"

func main() {
    fs := http.FileServer(http.Dir(dir))
    log.Print("Serving " + dir + " on http://localhost:8080")
    http.ListenAndServe(":8080", http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
        resp.Header().Add("Cache-Control", "no-cache")
        if strings.HasSuffix(req.URL.Path, ".wasm") {
            resp.Header().Set("content-type", "application/wasm")
        }
        fs.ServeHTTP(resp, req)
    }))
}

和 JS 代碼為:

const go = new Go(); // Defined in wasm_exec.js

go.importObject.env = {
    'main.add': function(x, y) {
        return x + y
    }
    // ... other functions
}


const WASM_URL = 'main.wasm';

var wasm;

if ('instantiateStreaming' in WebAssembly) {
    WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject).then(function (obj) {
        wasm = obj.instance;
        go.run(wasm);
    })
} else {
    fetch(WASM_URL).then(resp =>
        resp.arrayBuffer()
    ).then(bytes =>
        WebAssembly.instantiate(bytes, go.importObject).then(function (obj) {
            wasm = obj.instance;
            go.run(wasm);
        })
    )
}

// Calling the multiply function:
console.log('multiplied two numbers:', exports.multiply(5, 3));

我得到的輸出是: 在此處輸入圖片說明

我找到了解決方案,我需要一些東西來檢測並確認wasm已加載並准備好進行處理,與 JS 中用於檢查文檔是否准備就緒的方法相同:

if (document.readyState === 'complete') {
  // The page is fully loaded
}

// or

document.onreadystatechange = () => {
  if (document.readyState === 'complete') {
    // document ready
  }
};

因此,由於我的代碼中的wasm啟動函數是async我在 JS 中使用了以下內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>WASM</title>
    <!-- WASM -->
    <script src="http://localhost:8080/www/wasm_exec.js"></script>
    <script src="http://localhost:8080/www/loadWasm.js"></script>
</head>
<body>
</body>
<script>
    (async () => {
        try {
            await init();
            alert("Wasm had been loaded")
            console.log(multiply(5, 3));
        } catch (e) {
            console.log(e);
        } 
    })(); 

/***** OR ****/
    (async () => {
        await init();
        alert("Wasm had been loaded")
        console.log(multiply(5, 3));
    })().catch(e => {
        console.log(e);
    });
/*************/
</script>
</html>

這幫助我確定文檔已准備好處理並調用 wasm 函數。

wasm加載函數簡單地變成了:

async function init(){
    const go = new Go();
    const result = await WebAssembly.instantiateStreaming(
        fetch("http://localhost:8080/www/main.wasm"),
        go.importObject
    );
    go.run(result.instance); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM