[英]How to call an external js function from Wasm?
I am attempting to call a javascript function from Wasm.我正在尝试从 Wasm 调用 javascript function。
package main
import (
"syscall/js"
)
func main(){
var args []js.Value
// set args here...
js.Global().Get("document").Call("function", "myFunction").Set("args", args)
}
Then in HTML I would include my javascript然后在 HTML 我将包括我的 javascript
<script src="./js/scripts.js"></script>
Where js/script.js
contains:其中js/script.js
包含:
function myFunction(args){
console.log(args);
}
How do I call myFunction from the Wasm code?如何从 Wasm 代码调用 myFunction?
I attempted the suggested solution but it gives me a syntax error.我尝试了建议的解决方案,但它给了我一个语法错误。
args := js.ValueOf([]interface{"foo", 42})
v := js.Global().Call("myFunction", args)
fmt.Println(v)
The terminal looks like终端看起来像
$ GOOS=js GOARCH=wasm go build -o ./ipickd.wasm ./wasm.go
# command-line-arguments
./wasm.go:44:33: syntax error: unexpected literal "foo", expecting method or interface name
You have a number of errors:您有许多错误:
Global()
function 的 scope 是Global()
Set
is used to set a property on a js.Value
, as mentioned in the docs , and is not needed here Set
用于在js.Value
上设置属性,如文档中所述,此处不需要Call
takes the function name and args as parameters, per the docs根据文档, Call
将 function 名称和参数作为参数[]js.Value
will probably not do what you want if you want to pass an array如果你想传递一个数组, []js.Value
可能不会做你想做的事Your go code should be:您的 go 代码应为:
args := js.ValueOf([]interface{}{"foo", 42})
js.Global().Call("myFunction", args)
Or with a one-liner, letting Call
do the conversion:或者使用单线,让Call
进行转换:
js.Global().Call("myFunction", []interface{}{"foo", "42"})
You can refer to the js.ValueOf documentation for type compatibility.您可以参考js.ValueOf文档了解类型兼容性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.