Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can i let javascript call native function? #46

Open
rocket049 opened this issue Nov 1, 2018 · 0 comments
Open

can i let javascript call native function? #46

rocket049 opened this issue Nov 1, 2018 · 0 comments

Comments

@rocket049
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant