4

I have written a simple package in Go and I have compiled with gopherJS .

I have then included it my HTML via

<script src="./testgopher.js">

It has been loaded and all is well. But I am not sure how I can reuse a go function that has been declared in one of packages inside my own javascript.

What I want to do is in another script tag

<script> testpkg.Testfunc() </script>

where the testpkg and Testfunc have been written in go.

I tried to look into the window object and it doesnt look like the function has been added to window.

kostix
  • 51,517
  • 14
  • 93
  • 176
prk68
  • 176
  • 11
  • 2
    Looks like https://github.com/gopherjs/gopherjs#providing-library-functions-for-use-in-other-javascript-code – kostix Mar 22 '18 at 10:54

1 Answers1

4

First you have to register your function if you want to call it from JavaScript. For that you may use the js.Global variable.

Let's see a simple Go function called Hello() which writes the "Hello World!" text into the main document:

import "github.com/gopherjs/gopherjs/js"

func Hello() {
    js.Global.Get("document").Call("write", "Hello World!")
}

Then in your Go main() function you can register it like this:

func main() {
    js.Global.Set("Hello", Hello)
}

After this registration, the "Hello" identifier will be available to you in JavaScript. Since we registered a Go function value (Hello) to this identifier, it will also be a function in JavaScript which you can simply call like this:

<script>
    Hello();
</script>
icza
  • 389,944
  • 63
  • 907
  • 827