jchv / go-webview2

WebView2 bindings for pure Go, without CGo, based on the webview/webview bindings.
Other
264 stars 64 forks source link

How can I do js binding #48

Closed hajsf closed 2 years ago

hajsf commented 2 years ago

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!

jchv commented 2 years ago

If you call:

w.Bind("ps", printSomething)

You should be able to do:

<script>
    window.ps("test");
</script>
jchv commented 2 years ago

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.