using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CefSharp; using CefSharp.Event; using CefSharp.Wpf; namespace CEFHelpers { public class Helper { private ChromiumWebBrowser browser; public Helper(ChromiumWebBrowser browser) { this.browser = browser; browser.JavascriptObjectRepository.ObjectBoundInJavascript += ObjectBound; } public async Task EnsureRegistered(params String[] names) {//not sure if we need to consider context while (!browser.CanExecuteJavascriptInMainFrame) { await Task.Delay(100); } var js_cmd = $@"CefSharp.BindObjectAsync('{String.Join("','", names)}');"; var tasks = new List(); lock (obj_bound_tasks) { foreach (var name in names) { if (obj_bound_tasks.TryGetValue(name, out var tsk_src)) { if (tsk_src.Task.IsCompleted) tsk_src = null; } if (tsk_src == null) { tsk_src = new TaskCompletionSource(); obj_bound_tasks[name] = tsk_src; } tasks.Add(tsk_src.Task); } } browser.ExecuteScriptAsync(js_cmd); await Task.WhenAll(tasks); } private Dictionary> obj_bound_tasks = new Dictionary>(); private void ObjectBound(object sender, JavascriptBindingEventArgs e) { var name = e.ObjectName; lock (obj_bound_tasks) { if (obj_bound_tasks.TryGetValue(name, out var tsk_src)) { tsk_src.SetResult(true); obj_bound_tasks.Remove(name); } } } } }