Call JavaScript from Go WebAssembly using the syscall/js package to access global objects and invoke methods.
You call JavaScript from Go WebAssembly by using the syscall/js package to reference a global JavaScript object and invoke its methods.
package main
import (
"syscall/js"
)
func main() {
window := js.Global().Get("window")
window.Call("alert", "Hello from Go!")
}
Compile your Go code with GOOS=js GOARCH=wasm go build -o main.wasm and load the resulting .wasm file in a browser using a Go runtime loader.
Calling JavaScript from Go Wasm allows your Go program running in a web browser to talk to the browser's built-in JavaScript features. Think of it as a bridge where Go sends a message to JavaScript to perform an action, like showing a pop-up alert or reading a value from the webpage. You use this whenever your Go code needs to interact with the user interface or browser APIs.