Reputation: 1401
I am attempting to call a javascript function from Wasm.
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
<script src="./js/scripts.js"></script>
Where js/script.js
contains:
function myFunction(args){
console.log(args);
}
How do I call myFunction from the Wasm code?
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
Upvotes: 0
Views: 2033
Reputation: 21045
You have a number of errors:
Global()
Set
is used to set a property on a js.Value
, as mentioned in the docs, and is not needed hereCall
takes the function name and args as parameters, per the docs[]js.Value
will probably not do what you want if you want to pass an arrayYour go code should be:
args := js.ValueOf([]interface{}{"foo", 42})
js.Global().Call("myFunction", args)
Or with a one-liner, letting Call
do the conversion:
js.Global().Call("myFunction", []interface{}{"foo", "42"})
You can refer to the js.ValueOf documentation for type compatibility.
Upvotes: 2