简体   繁体   中英

How to call an external js function from Wasm?

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

You have a number of errors:

  • the scope for the function is Global()
  • Set is used to set a property on a js.Value , as mentioned in the docs , and is not needed here
  • Call 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 array

Your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM