/// <summary> /// Asks the server whether there is an update. /// </summary> /// <returns></returns> public Task <UpdateCheckResult> CheckForUpdatesAsync() { var taskCompletionSource = new TaskCompletionSource <UpdateCheckResult>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <UpdateCheckResult>("autoUpdaterCheckForUpdatesComplete" + guid, (updateCheckResult) => { try { BridgeConnector.Off("autoUpdaterCheckForUpdatesComplete" + guid); BridgeConnector.Off("autoUpdaterCheckForUpdatesError" + guid); taskCompletionSource.SetResult(updateCheckResult); } catch (Exception ex) { taskCompletionSource.SetException(ex); } }); BridgeConnector.On <string>("autoUpdaterCheckForUpdatesError" + guid, (error) => { BridgeConnector.Off("autoUpdaterCheckForUpdatesComplete" + guid); BridgeConnector.Off("autoUpdaterCheckForUpdatesError" + guid); string message = "An error occurred in CheckForUpdatesAsync"; if (error != null && !string.IsNullOrEmpty(error.ToString())) { message = JsonConvert.SerializeObject(error); } taskCompletionSource.SetException(new Exception(message)); }); BridgeConnector.Emit("autoUpdaterCheckForUpdates", guid); return(taskCompletionSource.Task); }
/// <summary> /// A BrowserView can be used to embed additional web content into a BrowserWindow. /// It is like a child window, except that it is positioned relative to its owning window. /// It is meant to be an alternative to the webview tag. /// </summary> /// <param name="options"></param> /// <returns></returns> public Task <BrowserView> CreateBrowserViewAsync(BrowserViewConstructorOptions options) { var taskCompletionSource = new TaskCompletionSource <BrowserView>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <int>("BrowserViewCreated", (id) => { BridgeConnector.Off("BrowserViewCreated"); BrowserView browserView = new BrowserView(id); _browserViews.Add(browserView); taskCompletionSource.SetResult(browserView); }); var keepDefaultValuesSerializer = new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include }; BridgeConnector.Emit("createBrowserView", JObject.FromObject(options, keepDefaultValuesSerializer)); return(taskCompletionSource.Task); }
/// <summary> /// Shows a message box, it will block the process until the message box is closed. /// It returns the index of the clicked button. If a callback /// is passed, the dialog will not block the process. /// </summary> /// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param> /// <param name="messageBoxOptions"></param> /// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns> public Task <MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, MessageBoxOptions messageBoxOptions) { var taskCompletionSource = new TaskCompletionSource <MessageBoxResult>(TaskCreationOptions.RunContinuationsAsynchronously); var guid = Guid.NewGuid().ToString(); BridgeConnector.On <MessageBoxResponse>("showMessageBoxComplete" + guid, (args) => { BridgeConnector.Off("showMessageBoxComplete" + guid); taskCompletionSource.SetResult(new MessageBoxResult { Response = args.response, CheckboxChecked = args.@checked }); }); if (browserWindow == null) { BridgeConnector.Emit("showMessageBox", messageBoxOptions, guid); } else { BridgeConnector.Emit("showMessageBox", browserWindow, messageBoxOptions, guid); } return(taskCompletionSource.Task); }
/// <summary> /// Execute native JavaScript/TypeScript code. /// </summary> /// <param name="socketEventName">Socket name registered on the host.</param> /// <param name="arguments">Optional parameters.</param> public void Call(string socketEventName, params dynamic[] arguments) { BridgeConnector.On <string>(socketEventName + "Error" + oneCallguid, (result) => { BridgeConnector.Off(socketEventName + "Error" + oneCallguid); Electron.Dialog.ShowErrorBox("Host Hook Exception", result); }); BridgeConnector.Emit(socketEventName, arguments, oneCallguid); }
/// <summary> /// Sets the application's dock menu. /// </summary> public void SetMenu(MenuItem[] menuItems) { menuItems.AddMenuItemsId(); BridgeConnector.Emit("dock-setMenu", JArray.FromObject(menuItems, _jsonSerializer)); _items.AddRange(menuItems); BridgeConnector.Off("dockMenuItemClicked"); BridgeConnector.On <string>("dockMenuItemClicked", (id) => { MenuItem menuItem = _items.GetMenuItem(id); menuItem?.Click(); }); }
/// <summary> /// Show the given file in a file manager. If possible, select the file. /// </summary> /// <param name="fullPath">The full path to the directory / file.</param> public Task ShowItemInFolderAsync(string fullPath) { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On("shell-showItemInFolderCompleted", () => { BridgeConnector.Off("shell-showItemInFolderCompleted"); }); BridgeConnector.Emit("shell-showItemInFolder", fullPath); return(taskCompletionSource.Task); }
/// <summary> /// The keys are the extension names and each value is an object containing name and version properties. /// Note: This API cannot be called before the ready event of the app module is emitted. /// </summary> /// <returns></returns> public Task <ChromeExtensionInfo[]> GetAllExtensionsAsync() { var taskCompletionSource = new TaskCompletionSource <ChromeExtensionInfo[]>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <ChromeExtensionInfo[]>("webContents-session-getAllExtensions-completed", (extensionslist) => { BridgeConnector.Off("webContents-session-getAllExtensions-completed"); taskCompletionSource.SetResult(extensionslist); }); BridgeConnector.Emit("webContents-session-getAllExtensions", Id); return(taskCompletionSource.Task); }
/// <summary> /// Shows the Traybar. /// </summary> /// <param name="image">The image.</param> /// <param name="menuItems">The menu items.</param> public void Show(string image, MenuItem[] menuItems) { menuItems.AddMenuItemsId(); BridgeConnector.Emit("create-tray", image, JArray.FromObject(menuItems, _jsonSerializer)); _items.Clear(); _items.AddRange(menuItems); BridgeConnector.Off("trayMenuItemClicked"); BridgeConnector.On <string>("trayMenuItemClicked", (id) => { MenuItem menuItem = _items.GetMenuItem(id.ToString()); menuItem?.Click(); }); }
/// <summary> /// Whether or not desktop notifications are supported on the current system. /// </summary> /// <returns></returns> public Task <bool> IsSupportedAsync() { var taskCompletionSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <bool>("notificationIsSupportedComplete", (isSupported) => { BridgeConnector.Off("notificationIsSupportedComplete"); taskCompletionSource.SetResult(isSupported); }); BridgeConnector.Emit("notificationIsSupported"); return(taskCompletionSource.Task); }
/// <summary> /// Sets the proxy settings. When pacScript and proxyRules are provided together, /// the proxyRules option is ignored and pacScript configuration is applied. /// </summary> /// <param name="config"></param> /// <returns></returns> public Task SetProxyAsync(ProxyConfig config) { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On("webContents-session-setProxy-completed" + guid, () => { BridgeConnector.Off("webContents-session-setProxy-completed" + guid); taskCompletionSource.SetResult(null); }); BridgeConnector.Emit("webContents-session-setProxy", Id, config, guid); return(taskCompletionSource.Task); }
/// <summary> /// Resolves the proxy information for url. The callback will be called with /// callback(proxy) when the request is performed. /// </summary> /// <param name="url"></param> /// <returns></returns> public Task <string> ResolveProxyAsync(string url) { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <string>("webContents-session-resolveProxy-completed" + guid, (proxy) => { BridgeConnector.Off("webContents-session-resolveProxy-completed" + guid); taskCompletionSource.SetResult(proxy.ToString()); }); BridgeConnector.Emit("webContents-session-resolveProxy", Id, url, guid); return(taskCompletionSource.Task); }
/// <summary> /// /// </summary> /// <returns></returns> public Task <string> GetUserAgent() { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <string>("webContents-session-getUserAgent-completed" + guid, (userAgent) => { BridgeConnector.Off("webContents-session-getUserAgent-completed" + guid); taskCompletionSource.SetResult(userAgent.ToString()); }); BridgeConnector.Emit("webContents-session-getUserAgent", Id, guid); return(taskCompletionSource.Task); }
/// <summary> /// Get session's current cache size. /// </summary> /// <returns>Callback is invoked with the session's current cache size.</returns> public Task <int> GetCacheSizeAsync() { var taskCompletionSource = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <int>("webContents-session-getCacheSize-completed" + guid, (size) => { BridgeConnector.Off("webContents-session-getCacheSize-completed" + guid); taskCompletionSource.SetResult(size); }); BridgeConnector.Emit("webContents-session-getCacheSize", Id, guid); return(taskCompletionSource.Task); }
/// <summary> /// /// </summary> /// <param name="identifier"></param> /// <returns></returns> public Task <int[]> GetBlobDataAsync(string identifier) { var taskCompletionSource = new TaskCompletionSource <int[]>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <int[]>("webContents-session-getBlobData-completed" + guid, (buffer) => { BridgeConnector.Off("webContents-session-getBlobData-completed" + guid); taskCompletionSource.SetResult(buffer); }); BridgeConnector.Emit("webContents-session-getBlobData", Id, identifier, guid); return(taskCompletionSource.Task); }
/// <summary> /// Open the given file in the desktop's default manner. /// </summary> /// <param name="path">The path to the directory / file.</param> /// <returns>The error message corresponding to the failure if a failure occurred, otherwise <see cref="string.Empty"/>.</returns> public Task <string> OpenPathAsync(string path) { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <string>("shell-openPathCompleted", (errorMessage) => { BridgeConnector.Off("shell-openPathCompleted"); taskCompletionSource.SetResult(errorMessage); }); BridgeConnector.Emit("shell-openPath", path); return(taskCompletionSource.Task); }
/// <summary> /// Clears the session’s HTTP authentication cache. /// </summary> public Task ClearAuthCacheAsync() { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On("webContents-session-clearAuthCache-completed" + guid, () => { BridgeConnector.Off("webContents-session-clearAuthCache-completed" + guid); taskCompletionSource.SetResult(null); }); BridgeConnector.Emit("webContents-session-clearAuthCache", Id, guid); return(taskCompletionSource.Task); }
/// <summary> /// Feed URL. /// </summary> /// <returns>Feed URL.</returns> public Task <string> GetFeedURLAsync() { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <string>("autoUpdaterGetFeedURLComplete" + guid, (downloadedPath) => { BridgeConnector.Off("autoUpdaterGetFeedURLComplete" + guid); taskCompletionSource.SetResult(downloadedPath.ToString()); }); BridgeConnector.Emit("autoUpdaterGetFeedURL", guid); return(taskCompletionSource.Task); }
/// <summary> /// resolves when the extension is loaded. /// /// This method will raise an exception if the extension could not be loaded.If /// there are warnings when installing the extension (e.g. if the extension requests /// an API that Electron does not support) then they will be logged to the console. /// /// Note that Electron does not support the full range of Chrome extensions APIs. /// See Supported Extensions APIs for more details on what is supported. /// /// Note that in previous versions of Electron, extensions that were loaded would be /// remembered for future runs of the application.This is no longer the case: /// `loadExtension` must be called on every boot of your app if you want the /// extension to be loaded. /// /// This API does not support loading packed (.crx) extensions. /// ///** Note:** This API cannot be called before the `ready` event of the `app` module /// is emitted. /// ///** Note:** Loading extensions into in-memory(non-persistent) sessions is not supported and will throw an error. /// </summary> /// <param name="path">Path to the Chrome extension</param> /// <param name="allowFileAccess">Whether to allow the extension to read local files over `file://` protocol and /// inject content scripts into `file://` pages. This is required e.g. for loading /// devtools extensions on `file://` URLs. Defaults to false.</param> /// <returns></returns> public Task <Extension> LoadExtensionAsync(string path, bool allowFileAccess = false) { var taskCompletionSource = new TaskCompletionSource <Extension>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <Extension>("webContents-session-loadExtension-completed", (extension) => { BridgeConnector.Off("webContents-session-loadExtension-completed"); taskCompletionSource.SetResult(extension); }); BridgeConnector.Emit("webContents-session-loadExtension", Id, path, allowFileAccess); return(taskCompletionSource.Task); }
/// <summary> /// Sends a request to get all cookies matching filter, and resolves a callack with the response. /// </summary> /// <param name="filter"> /// </param> /// <returns>A task which resolves an array of cookie objects.</returns> public Task <Cookie[]> GetAsync(CookieFilter filter) { var taskCompletionSource = new TaskCompletionSource <Cookie[]>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <Cookie[]>("webContents-session-cookies-get-completed" + guid, (cookies) => { BridgeConnector.Off("webContents-session-cookies-get-completed" + guid); taskCompletionSource.SetResult(cookies); }); BridgeConnector.Emit("webContents-session-cookies-get", Id, filter, guid); return(taskCompletionSource.Task); }
/// <summary> /// On macOS, this displays a modal dialog that shows a message and certificate information, /// and gives the user the option of trusting/importing the certificate. If you provide a /// browserWindow argument the dialog will be attached to the parent window, making it modal. /// </summary> /// <param name="browserWindow"></param> /// <param name="options"></param> /// <returns></returns> public Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options) { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On("showCertificateTrustDialogComplete" + guid, () => { BridgeConnector.Off("showCertificateTrustDialogComplete" + guid); taskCompletionSource.SetResult(null); }); BridgeConnector.Emit("showCertificateTrustDialog", browserWindow, options, guid); return(taskCompletionSource.Task); }
/// <summary> /// /// </summary> /// <param name="details"></param> /// <returns></returns> public Task SetAsync(CookieDetails details) { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On("webContents-session-cookies-set-completed" + guid, () => { BridgeConnector.Off("webContents-session-cookies-set-completed" + guid); taskCompletionSource.SetResult(null); }); BridgeConnector.Emit("webContents-session-cookies-set", Id, details, guid); return(taskCompletionSource.Task); }
/// <summary> /// Removes the cookies matching url and name /// </summary> /// <param name="url">The URL associated with the cookie.</param> /// <param name="name">The name of cookie to remove.</param> /// <returns>A task which resolves when the cookie has been removed</returns> public Task RemoveAsync(string url, string name) { var taskCompletionSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On("webContents-session-cookies-remove-completed" + guid, () => { BridgeConnector.Off("webContents-session-cookies-remove-completed" + guid); taskCompletionSource.SetResult(null); }); BridgeConnector.Emit("webContents-session-cookies-remove", Id, url, name, guid); return(taskCompletionSource.Task); }
/// <summary> /// Dialog for save files. /// </summary> /// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param> /// <param name="options"></param> /// <returns>Returns String, the path of the file chosen by the user, if a callback is provided it returns an empty string.</returns> public Task <string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options) { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <string>("showSaveDialogComplete" + guid, (filename) => { BridgeConnector.Off("showSaveDialogComplete" + guid); taskCompletionSource.SetResult(filename); }); BridgeConnector.Emit("showSaveDialog", browserWindow, options, guid); return(taskCompletionSource.Task); }
/// <summary> /// Sets the application menu. /// </summary> /// <param name="menuItems">The menu items.</param> public void SetApplicationMenu(MenuItem[] menuItems) { _menuItems.Clear(); menuItems.AddMenuItemsId(); menuItems.AddSubmenuTypes(); BridgeConnector.Emit("menu-setApplicationMenu", JArray.FromObject(menuItems, _jsonSerializer)); _menuItems.AddRange(menuItems); BridgeConnector.Off("menuItemClicked"); BridgeConnector.On <string>("menuItemClicked", (id) => { MenuItem menuItem = _menuItems.GetMenuItem(id); menuItem.Click?.Invoke(); }); }
/// <summary> /// Listens to channel, when a new message arrives listener would be called with /// listener(event, args...). /// </summary> /// <param name="channel">Channelname.</param> /// <param name="listener">Callback Method.</param> public void On(string channel, Action <object> listener) { BridgeConnector.Emit("registerIpcMainChannel", channel); BridgeConnector.Off(channel); BridgeConnector.On <object[]>(channel, (args) => { var objectArray = FormatArguments(args); if (objectArray.Count == 1) { listener(objectArray.First()); } else { listener(objectArray); } }); }
/// <summary> /// Registers a global shortcut of accelerator. /// The callback is called when the registered shortcut is pressed by the user. /// /// When the accelerator is already taken by other applications, this call will /// silently fail.This behavior is intended by operating systems, since they don’t /// want applications to fight for global shortcuts. /// </summary> public void Register(string accelerator, Action function) { if (!_shortcuts.ContainsKey(accelerator)) { _shortcuts.Add(accelerator, function); BridgeConnector.Off("globalShortcut-pressed"); BridgeConnector.On <string>("globalShortcut-pressed", (shortcut) => { if (_shortcuts.ContainsKey(shortcut)) { _shortcuts[shortcut.ToString()](); } }); BridgeConnector.Emit("globalShortcut-register", accelerator); } }
/// <summary> /// Sets the context menu. /// </summary> /// <param name="browserWindow">The browser window.</param> /// <param name="menuItems">The menu items.</param> public void SetContextMenu(BrowserWindow browserWindow, MenuItem[] menuItems) { menuItems.AddMenuItemsId(); menuItems.AddSubmenuTypes(); BridgeConnector.Emit("menu-setContextMenu", browserWindow.Id, JArray.FromObject(menuItems, _jsonSerializer)); if (!_contextMenuItems.ContainsKey(browserWindow.Id)) { _contextMenuItems.Add(browserWindow.Id, menuItems.ToList()); var x = _contextMenuItems.ToDictionary(kv => kv.Key, kv => kv.Value.AsReadOnly()); ContextMenuItems = new ReadOnlyDictionary <int, ReadOnlyCollection <MenuItem> >(x); } BridgeConnector.Off("contextMenuItemClicked"); BridgeConnector.On <MenuResponse>("contextMenuItemClicked", (results) => { MenuItem menuItem = _contextMenuItems[results.windowId].GetMenuItem(results.id); menuItem.Click?.Invoke(); }); }
/// <summary> /// Note: On Windows and Linux an open dialog can not be both a file selector /// and a directory selector, so if you set properties to ['openFile', 'openDirectory'] /// on these platforms, a directory selector will be shown. /// </summary> /// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param> /// <param name="options"></param> /// <returns>An array of file paths chosen by the user</returns> public Task <string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options) { var taskCompletionSource = new TaskCompletionSource <string[]>(TaskCreationOptions.RunContinuationsAsynchronously); string guid = Guid.NewGuid().ToString(); BridgeConnector.On <string[]>("showOpenDialogComplete" + guid, (filePaths) => { BridgeConnector.Off("showOpenDialogComplete" + guid); var list = new List <string>(); foreach (var item in filePaths) { list.Add(HttpUtility.UrlDecode(item)); } taskCompletionSource.SetResult(list.ToArray()); }); BridgeConnector.Emit("showOpenDialog", browserWindow, options, guid); return(taskCompletionSource.Task); }
/// <summary> /// Open the given external protocol URL in the desktop’s default manner. /// (For example, mailto: URLs in the user’s default mail agent). /// </summary> /// <param name="url">Max 2081 characters on windows.</param> /// <param name="options">Controls the behavior of OpenExternal.</param> /// <returns>The error message corresponding to the failure if a failure occurred, otherwise <see cref="string.Empty"/>.</returns> public Task <string> OpenExternalAsync(string url, OpenExternalOptions options) { var taskCompletionSource = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On <string>("shell-openExternalCompleted", (error) => { BridgeConnector.Off("shell-openExternalCompleted"); taskCompletionSource.SetResult(error); }); if (options == null) { BridgeConnector.Emit("shell-openExternal", url); } else { BridgeConnector.Emit("shell-openExternal", url, options); } return(taskCompletionSource.Task); }
/// <summary> /// The async method will resolve when the page has finished loading, /// and rejects if the page fails to load. /// /// A noop rejection handler is already attached, which avoids unhandled rejection /// errors. /// /// Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. /// the `http://` or `file://`. If the load should bypass http cache then use the /// `pragma` header to achieve it. /// </summary> /// <param name="url"></param> /// <param name="options"></param> public Task LoadURLAsync(string url, LoadURLOptions options) { var taskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); BridgeConnector.On("webContents-loadURL-complete" + Id, () => { BridgeConnector.Off("webContents-loadURL-complete" + Id); BridgeConnector.Off("webContents-loadURL-error" + Id); taskCompletionSource.SetResult(); }); BridgeConnector.On <string>("webContents-loadURL-error" + Id, (error) => { BridgeConnector.Off("webContents-loadURL-error" + Id); BridgeConnector.Off("webContents-loadURL-complete" + Id); taskCompletionSource.SetException(new InvalidOperationException(error.ToString())); }); BridgeConnector.Emit("webContents-loadURL", Id, url, options); return(taskCompletionSource.Task); }