go-webview2 icon indicating copy to clipboard operation
go-webview2 copied to clipboard

How can I do js binding

Open hajsf opened this issue 3 years ago • 1 comments

I've the below:

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/jchv/go-webview2" // go install github.com/jchv/go-webview2@latest
)

func main() {
	w := webview2.NewWithOptions(webview2.WebViewOptions{
		Window:    nil,
		Debug:     false,
		DataPath:  "",
		AutoFocus: true,
		WindowOptions: webview2.WindowOptions{
			Title:  "Minimal webview example",
			Width:  800,
			Height: 600,
			IconId: 2,
			Center: true},
	})
	if w == nil {
		log.Fatalln("Failed to load webview.")
	}
	defer w.Destroy()

	http.HandleFunc("/", index)

	go http.ListenAndServe(":1234", nil)

	/*	w.Init("alert('hi')")
		w.Bind("ps", printSomething)
		w.SetTitle("Golang WebView 2 example")
		w.SetSize(800, 600, webview2.HintFixed)
		w.Navigate("http://localhost:1234/")
	*/
	// The window will be displayed once and then resized to this size.
	w.SetSize(600, 600, webview2.HintNone)
	// load a local HTML file.
	c, err := os.Getwd()
	if err != nil {
		log.Fatalln(err.Error())
	}
	w.Navigate(filepath.Join(c, "templates/index.html"))

	w.Bind("ps", printSomething)

	w.Run()
}

func index(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello"))
}

func printSomething(name string) {
	now := time.Now().Format(time.Stamp)
	fmt.Println(textMessage(name, now))
	// w.Eval(fmt.Sprintf("setDivContent('output', '%s')", htmlMessage(name, now)))
}

func textMessage(name, time string) string {
	return fmt.Sprintf(">>> [%s] Hello, %s.", time, name)
}

func htmlMessage(name, time string) string {
	escapedName := strings.ReplaceAll(name, "'", "'")
	return fmt.Sprintf(`Hello, <b>%s</b>. The current time is <span class="blue">%s</span>. Check your console window for a message.`, escapedName, time)
}

And

<!DOCTYPE>
<html> 
  <head>
    <title>Hello World</title> 
  </head>

  <body> 
    <h1>Hello World</h1> 
  </body>
  <script>
      // how to call the printSomething function!!
  </script>
</html>

I want to define the printSomething function, but did not know how to make it understand the webview in the gofunction, and did not know how to make it call it in the JS function!

hajsf avatar Jun 24 '22 14:06 hajsf

If you call:

w.Bind("ps", printSomething)

You should be able to do:

<script>
    window.ps("test");
</script>

jchv avatar Jun 24 '22 15:06 jchv

I'm closing this since it was answered months ago and I haven't heard back; I hope the answer helped you. If not, feel free to re-open this issue.

jchv avatar Sep 25 '22 02:09 jchv