Skip to content

can i let javascript call native function? #46

@rocket049

Description

@rocket049

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions