Is it possible to explicitly call an exported Go WebAssembly function from JS?

后端 未结 1 1798
滥情空心
滥情空心 2021-02-09 19:46

Is it possible to call a Go WebAssembly function, other than main, in Javascript?

Let me first show what I did. My Go functions are defined

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 20:19

    Yes, it is possible. You can "export" a function to the global context (i.e. window in browser, global in nodejs):

    js.Global().Set("add", js.FuncOf(addFunction))
    

    Where "add" is the name that you can use to call the function from Javascript (window.add) and "addFunction" is a Go function in your Go code, next to your main.

    Note that "addFunction" must follow that method signature:

    package main
    
    import (
        "syscall/js"
    )
    
    func addFunction(this js.Value, p []js.Value) interface{} {
        sum := p[0].Int() + p[1].Int()
        return js.ValueOf(sum)
    }
    
    func main() {
        c := make(chan struct{}, 0)
    
        js.Global().Set("add", js.FuncOf(addFunction))
    
        <-c
    }
    

    After "go.run(result.instance);" you can run.

    go.run(result.instance);
    add(100,200);
    

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