evaluate.go RawHistoryFolder
1package webkit
2
3/*
4#cgo pkg-config: webkitgtk-6.0
5#include <webkit/webkit.h>
6#include <stdlib.h>
7*/
8import "C"
9import (
10 "unsafe"
11
12 javascriptcore "github.com/diamondburned/gotk4-webkitgtk/pkg/javascriptcore/v6"
13 webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6"
14 "github.com/diamondburned/gotk4/pkg/core/glib"
15)
16
17// EvaluateJavascript executes JavaScript code in the WebView in the default world
18// This is a wrapper around webkit_web_view_evaluate_javascript that wasn't generated by gotk4
19func EvaluateJavascript(view *webkit.WebView, script string) {
20 EvaluateJavascriptInWorld(view, script, "")
21}
22
23// EvaluateJavascriptInWorld executes JavaScript code in a specific world
24// Pass empty string for worldName to use the main/page world
25func EvaluateJavascriptInWorld(view *webkit.WebView, script string, worldName string) {
26 if view == nil {
27 return
28 }
29
30 // Get the underlying GObject pointer from the gotk4 WebView
31 obj := glib.BaseObject(view)
32 if obj == nil {
33 return
34 }
35
36 nativePtr := obj.Native()
37 if nativePtr == 0 {
38 return
39 }
40
41 cScript := C.CString(script)
42 defer C.free(unsafe.Pointer(cScript))
43
44 var cWorldName *C.char
45 if worldName != "" {
46 cWorldName = C.CString(worldName)
47 defer C.free(unsafe.Pointer(cWorldName))
48 }
49
50 // Call webkit_web_view_evaluate_javascript
51 // Parameters: web_view, script, length, world_name, source_uri, cancellable, callback, user_data
52 C.webkit_web_view_evaluate_javascript(
53 (*C.WebKitWebView)(unsafe.Pointer(nativePtr)),
54 cScript,
55 C.gssize(-1), // -1 means null-terminated string
56 cWorldName, // world_name (NULL for main world, or specific world name)
57 nil, // source_uri (NULL)
58 nil, // cancellable (NULL)
59 nil, // callback (NULL for fire-and-forget)
60 nil, // user_data (NULL)
61 )
62}
63
64// JSCValueToString converts a JSCValue from a GTK signal to a Go string
65func JSCValueToString(value interface{}) string {
66 if value == nil {
67 return ""
68 }
69
70 // Type assert to *javascriptcore.Value from gotk4 bindings
71 jscValue, ok := value.(*javascriptcore.Value)
72 if !ok {
73 return ""
74 }
75
76 // Use the gotk4 String() method to convert JSCValue to string
77 return jscValue.String()
78}