public async Task <string> ExecuteScriptAsync(string script) { var taskResult = new TaskCompletionSource <string>(); var id = Guid.NewGuid(); GAsyncReadyDelegate callback = (IntPtr webview, IntPtr asyncResult, IntPtr userdata) => { try { taskResult.SetResult(ExecuteScriptCallback(webview, asyncResult, userdata)); } catch (Exception ex) { taskResult.SetException(ex); } }; scriptCallbacks.TryAdd(id, callback); using (GLibString gfunction = script) { WebKit.JavaScript.BeginExecute(Handle, gfunction, IntPtr.Zero, callback, IntPtr.Zero); } // found no other solution than the ConccurentDictionary one to keep the callbacks from getting garbage collected // GC.KeepAlive(callback) works not all the time var result = await taskResult.Task; scriptCallbacks.TryRemove(id, out var _); return(result); }
public GtkWebview(WebviewBridge bridge) { this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); // need to keep the delegates around or they will get garbage collected scriptDelegate = ScriptCallback; loadFailedDelegate = LoadFailedCallback; loadDelegate = LoadCallback; contextMenuDelegate = ContextMenuCallback; closeDelegate = CloseCallback; titleChangeDelegate = TitleChangeCallback; uriSchemeCallback = UriSchemeCallback; scriptExecuteCallback = ScriptExecuteCallback; manager = WebKit.Manager.Create(); GLib.ConnectSignal(manager, "script-message-received::external", scriptDelegate, IntPtr.Zero); using (GLibString name = "external") { WebKit.Manager.RegisterScriptMessageHandler(manager, name); } Handle = WebKit.CreateWithUserContentManager(manager); settings = WebKit.Settings.Get(Handle); inspector = WebKit.Inspector.Get(Handle); GLib.ConnectSignal(Handle, "load-failed", loadFailedDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "load-changed", loadDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "context-menu", contextMenuDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "close", closeDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "notify::title", titleChangeDelegate, IntPtr.Zero); const string scheme = "spidereye"; customHost = new Uri(UriTools.GetRandomResourceUrl(scheme)); IntPtr context = WebKit.Context.Get(Handle); using GLibString gscheme = scheme; WebKit.Context.RegisterUriScheme(context, gscheme, uriSchemeCallback, IntPtr.Zero, IntPtr.Zero); }
public static extern void BeginExecute(IntPtr webview, IntPtr js, IntPtr cancellable, GAsyncReadyDelegate callback, IntPtr user_data);