wailsapp / go-webview2

The Wails fork of go-webview2
Other
34 stars 17 forks source link

How to Pass a Callback Function When Calling `ExecuteScript`? #14

Open lanyeeee opened 2 months ago

lanyeeee commented 2 months ago

Is there any way to pass a callback function when calling ExecuteScript?

For example, consider the following code snippet. This code, of course, will panic during runtime. Could you please provide the correct way to do this?

callback := func(errorCode uintptr, resultObjectAsJson string) {
    // print error and result
}
_, _, err = e.webview.vtbl.ExecuteScript.Call(
    uintptr(unsafe.Pointer(e.webview)),
    uintptr(unsafe.Pointer(_script)),
    uintptr(unsafe.Pointer(&callback)),
)

In C++, similar code looks like this:

webview->ExecuteScript(script.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>([](HRESULT errorCode, LPCWSTR result) -> HRESULT {
    // print error and result
    return S_OK;
    }).Get());

However, I found that go-webview2 cannot even create ICoreWebView2ExecuteScriptCompletedHandler. Here's the complete code:

package main

import (
    "fmt"
    "github.com/wailsapp/go-webview2/pkg/webview2"
)

func main() {
    var handler webview2.ICoreWebView2ExecuteScriptCompletedHandler
    fmt.Printf("%+v\n", handler)
}

panic massage:

panic: compileCallback: argument size is larger than uintptr

goroutine 1 [running]:
syscall.compileCallback({0x6163a0?, 0x64ae70?}, 0xe0?)
    C:/Program Files/Go/src/runtime/syscall_windows.go:280 +0xca
syscall.NewCallback(...)
    C:/Program Files/Go/src/syscall/syscall_windows.go:214
golang.org/x/sys/windows.NewCallback(...)
    C:/Users/lanye/go/pkg/mod/golang.org/x/sys@v0.8.0/windows/syscall_windows.go:140
github.com/wailsapp/go-webview2/pkg/webview2.NewComProc(...)
    C:/Users/lanye/go/pkg/mod/github.com/wailsapp/go-webview2@v1.0.12/pkg/webview2/com.go:17
github.com/wailsapp/go-webview2/pkg/webview2.init()
    C:/Users/lanye/go/pkg/mod/github.com/wailsapp/go-webview2@v1.0.12/pkg/webview2/ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler.go:51 +0x113

The reason seems to be the id parameter of the function in the following code is of type string, and the error disappeared after I replaced it with uintptr, however, the similar situation is common in go-webview2.

https://github.com/wailsapp/go-webview2/blob/1cea6fa283522b953f44435a08c88da6ff35988b/pkg/webview2/ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler.go#L36-L43

In conclusion, I would like to know if there is any way to pass a callback function when calling ExecuteScript.

leaanthony commented 2 months ago

There is this method but it isn't supported just yet. Would happily accept a PR for it though...