sourcegraph / go-webkit2

WebKit API bindings (WebKitGTK+ v2) for Go
https://sourcegraph.com/github.com/sourcegraph/go-webkit2
Other
313 stars 61 forks source link

can i let javascript call native function? #46

Open rocket049 opened 5 years ago

rocket049 commented 5 years ago

my code not run correct.

//tryit.go
package main

import (
    "flag"
    "os"
)
import (
    "log"

    "github.com/gotk3/gotk3/glib"
    "github.com/gotk3/gotk3/gtk"
    "github.com/sourcegraph/go-webkit2/webkit2"
    "github.com/sqs/gojs"
)

func JsNative(s string) *gojs.Value {
    log.Printf("JS native : %s\n", s)
    return nil
}

func main() {
    flag.Parse()
    gtk.Init(&os.Args)
    win1, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    defer win1.Destroy()
    web1 := webkit2.NewWebView()
    defer web1.Destroy()
    win1.Add(web1)
    web1.Context().SetCacheModel(webkit2.WebBrowserCacheModel)
    web1.Settings().SetAutoLoadImages(false)
    web1.SetVisible(true)
    jscxt := web1.JavaScriptGlobalContext()
    js1 := jscxt.NewFunctionWithNative(JsNative)
    err := jscxt.SetProperty(jscxt.GlobalObject(), "jsNative1", js1.ToValue(), gojs.PropertyAttributeReadOnly)
    if err != nil {
        log.Println(err)
    }
    web1.Connect("load-failed", func() {
        log.Println("Load failed.")
    })
    web1.Connect("load-changed", func(_ *glib.Object, i int) {
        loadEvent := webkit2.LoadEvent(i)
        switch loadEvent {
        case webkit2.LoadFinished:
            web1.RunJavaScript("jsNative1('abcd')", func(result *gojs.Value, err error) {
                log.Println("jsNative1:", err)
                gtk.MainQuit()
            })
        }
    })
    URL := flag.Arg(0)
    glib.IdleAdd(func() bool {
        web1.LoadURI(URL)
        return false
    })
    gtk.Main()
}

i build it and run, the result is like follow:

./tryit https://www.baidu.com/
2018/11/01 16:19:29 jsNative1: TypeError: undefined is not a function