/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); var info = await HtmlPage.GetBrowserInformation(); var infoText = $"Name: {info.Name}<br />Browser Version: {info.BrowserVersion}<br />Platform: {info.Platform}<br />Cookies Enabled: {info.CookiesEnabled}<br />User Agent: {info.UserAgent}"; var paragraph = await document.GetElementById("info"); await paragraph.SetProperty("innerHTML", infoText); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); // Get a reference to the top-level <html> element. var element = await document.GetDocumentElement(); // Process the starting element reference await ProcessElement(element, 0); await console.Log(elementTree); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { IpcRenderer ipcRenderer = await IpcRenderer.Create(); await console.Log(await ipcRenderer.SendSync("synchronous-message", "synchronous ping")); // prints "pong" ipcRenderer.On("asynchronous-reply", (async(args) => { var argsArray = args as object[]; await console.Log(argsArray[1]); // prints "pong" return(null); })); await ipcRenderer.Send("asynchronous-message", "asynchronous ping"); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { // Get a reference to the HTML DOM document. var document = await HtmlPage.GetDocument(); // Get a reference to the body element. var body = await document.GetElementById("docBody"); // Create a <main> type element var mainElement = await document.CreateElement("main"); // Append the newly created element to the page DOM await body.AppendChild(mainElement); // Get a collection of all the <main> type element in the page and using // Linq get the first of the collection. var content = (await document.GetElementsByTagName("main")).First(); // Get a collection of all the <link> elements var links = await document.QuerySelectorAll("link[rel=\"import\"]"); // Loop through all of the <link> elements found foreach (var link in links) { // Access the contents of the import document by examining the // import property of the corresponding <link> element var template = await link.GetProperty <HtmlElement>("import").ContinueWith( async(t) => { // For all imported contents obtain a reference to the <template> return(await t.Result?.QuerySelector(".task-template")); } ).Result; // Create a clone of the template’s content using the importNode property and // passing in the content of the template var clone = await document.Invoke <HtmlElement>("importNode", await template.GetProperty <HtmlElement>("content"), true); // Append the newly created cloned template to the content element. await content.AppendChild(clone); } } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { Func <object, Task <object> > listener1 = (async(commands) => { console.Log($"Listener 1 executed"); return(null); }); var eventEmitter = await EventEmitter.Create(); eventEmitter.AddListener("connection", listener1); eventEmitter.AddListener("connection", (async(commands) => { console.Log($"Listener 2 executed."); return(null); })); console.Log($"# of 'connection' listeners {await eventEmitter.ListenerCount("connection")}"); console.Log($"emitted {await eventEmitter.Emit("connection")}"); console.Log("Removing all listeners"); eventEmitter.RemoveAllListeners("connection"); console.Log($"# of 'connection' listeners {await eventEmitter.ListenerCount("connection")}"); eventEmitter.Once("foo", (async(x) => { console.Log("a"); return(null); })); eventEmitter.PrependOnceListener("foo", (async(x) => { console.Log("b"); return(null); })); eventEmitter.Emit("foo"); // Should be logged first b then a eventEmitter.Emit("foo"); // Listeners will not be called again. } catch (Exception exc) { console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); await app.On("activate", new ScriptObjectCallback <Event>(async(evt) => { // On OS X we will receive an activate event and if we already // have a window then we will just show it. if (mainWindow != null) { await mainWindow.Show(); } } )); // We need this for Mac functionality for Cmd-Q and Quit from app menu. // 'before-quit' is emitted when Electron receives // the signal to exit and wants to start closing windows await app.On("before-quit", new ScriptObjectCallback <Event>(async(evt) => { IsShouldQuit = true; } )); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { await CreateTray(__dirname); windowId = await CreateWindow(__dirname); } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); var webContents = await mainWindow.GetWebContents(); // Capture all external link clicks and open them in the // default browser instead of inline in our application. await webContents.On("will-navigate", new ScriptObjectCallback <Event, string>( async(navResult) => { var result = navResult.CallbackState as object[]; var ev = result[0] as Event; var externalURL = result[1].ToString(); ev.PreventDefault(); System.Diagnostics.Process.Start(externalURL); } ) ); } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); var printPDFBtn = await document.GetElementById("print-pdf"); var ipcRenderer = await IpcRenderer.Create(); await printPDFBtn?.AttachEvent("click", new EventHandler(async(sender, evt) => { await console.Log("clicked"); ipcRenderer.Send("print-to-pdf"); }) ); ipcRenderer.On("wrote-pdf", new IpcRendererEventListener(async(result) => { var state = result.CallbackState as object[]; var parms = state[1] as object[]; foreach (var parm in parms) { await console.Log(parm); } var pathLabel = await document.GetElementById("file-path"); await pathLabel.SetProperty("innerHTML", $"Wrote PDF to: {parms[0]}"); })); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { // Create the browser window. mainWindow = await BrowserWindow.Create(new BrowserWindowOptions() { Width = 600, Height = 400 }); // and load the index.html of the app. await mainWindow.LoadURL($"file://{__dirname}/index.html"); // Open the DevTools await mainWindow.GetWebContents().ContinueWith( (t) => { t.Result?.OpenDevTools(DevToolsMode.Bottom); } ); // Emitted when the window is closed. await mainWindow.On("closed", async (evt) => { await console.Log("Received closed event"); System.Console.WriteLine("Received closed event"); mainWindow = null; return(null); }); await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(await mainWindow.GetId()); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); area = await document.GetElementById("input"); output = await document.GetElementById("output"); spaces = await document.GetElementById("spaced"); emojiPicker = await document.GetElementById("emoji"); length = await document.GetElementById("length"); copy = await document.GetElementById("copy"); await area.AttachEvent("input", updateOutput); await spaces.AttachEvent("change", updateOutput); await emojiPicker.AttachEvent("change", updateOutput); await copy.AttachEvent("click", copyClicked); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { // Get a reference to the DOM Document var document = await HtmlPage.GetDocument(); // Get a reference to the "link" element var link = await document.GetElementById("link"); // Attach an event listener to the "click" event await link.AttachEvent("click", onMouseClick); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { IpcRenderer ipcRenderer = await IpcRenderer.Create(); // Note: Sending a synchronous message from the render process will block // the whole renderer process, unless you know what you are doing you should never use it. // // View notes in MainWindow.cs await console.Log(await ipcRenderer.SendSync("synchronous-message", "synchronous ping")); // prints "pong" ipcRenderer.On("asynchronous-reply", new IpcRendererEventListener(async(result) => { var state = result.CallbackState as object[]; var parms = state[1] as object[]; foreach (var parm in parms) { await console.Log(parm); // prints "pong" } })); await ipcRenderer.Send("asynchronous-message", "asynchronous ping"); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); // var web = await mainWindow.GetWebContents(); // var session = await web.GetSession(); // There are functionality differences between mac and windows. You will need to try // this to see if it works for you in all scenarios. For instance this works on a Mac, // at least it does on the ones that were tested, but windows always displays the save dialog. // await session.On("will-download", // new ScriptObjectCallback<Event, DownloadItem, WebContents>( // async (callbackResult) => // { // var cr = new WillDownloadResult(callbackResult); // await cr.DownloadItem.SetSavePath($"downloads/"); // var fileURL = await cr.DownloadItem.GetURL(); // await console.Log($"Downloading: {fileURL}"); // await HandleDownload(cr, fileURL); // } // ) // ); // attach a listener to download the file. var ipcMain = await IpcMain.Create(); ipcMain.On("download-file", new IpcMainEventListener ( async(result) => { var state = result.CallbackState as object[]; var ipcMainEvent = (IpcMainEvent)state[0]; var parms = state[1] as object[]; // foreach (var parm in parms) // System.Console.WriteLine($"\tparm: {parm}"); // Call the DownloadFile helper method await DownloadFile(parms[0].ToString()); } ) ); } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); window = await HtmlPage.GetWindow(); canvas = await document.QuerySelector("canvas"); canvasWidth = await canvas.GetProperty <int>("width"); canvasHeight = await canvas.GetProperty <int>("height"); ctx = await canvas.Invoke <HtmlObject> ("getContext", "2d"); animationCallback = new ScriptObjectCallback( async(ar) => { await CanvasDraw().ContinueWith( (t) => { animation = null; } ); } ); await CanvasDraw(); await canvas.AttachEvent("click", new EventHandler( async(sender, e) => { if ((await document.GetProperty <HtmlObject>("pointerLockElement"))?.Handle == canvas.Handle) { await document.Invoke <object>("exitPointerLock"); } else { await canvas.Invoke <object>("requestPointerLock"); } }) ); // Hook pointer lock state change events await document.AttachEvent("pointerlockchange", new EventHandler( async(sender, e) => { if ((await document.GetProperty <HtmlObject>("pointerLockElement"))?.Handle == canvas.Handle) { await console.Log("The pointer lock status is now locked"); await document.AttachEvent("mousemove", UpdatePosition); } else { await console.Log("The pointer lock status is now unlocked"); await document.DetachEvent("mousemove", UpdatePosition); } }) ); tracker = await document.GetElementById("tracker"); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); var findMe = await document.GetElementById("findMe"); var map = await document.GetElementById("map"); var location = await document.GetElementById("location"); var error = false; await findMe.AttachEvent(HtmlEventNames.Click, new EventHandler( async(sender, evt) => { error = false; await location.SetProperty("innerText", "Locating ..."); var geo = await GeoLocationAPI.Instance(); await geo.GetCurrentPosition( new ScriptObjectCallback <Position>( async(cr) => { // Obtain our position from the CallbackState var position = cr.CallbackState as Position; // Reference the Coordinates class var coords = position.Coordinates; // Create our location information string var posString = $"Your current position is:\nLatitude : {coords.Latitude}\nLongitude : {coords.Longitude}\nMore or less {coords.Accuracy} Meters."; // Set the location status text await location.SetProperty("innerText", posString); // Retrieve the image of the location using the longitude and latitude // properties of the Coordinates class. var imageURL = $"https://maps.googleapis.com/maps/api/staticmap?center={coords.Latitude},{coords.Longitude}&zoom=13&size=300x300&sensor=false"; // Set the src property of the <image> tag await map.SetProperty("src", imageURL); } ), new ScriptObjectCallback <PositionError>( async(cr) => { // Obtain the error from CallbackState var err = cr.CallbackState as PositionError; // Format a string with the error var errString = $"ERROR({err.ErrorCode}): {err.Message}"; // If we already have an error then we will want to append // the error to the already existing error(s) that exist. if (error) { var errorText = await location.GetProperty <string>("innerText"); errString = $"{errorText}\n{errString}"; } error = true; // Set the status area text for feedback to the user await location.SetProperty("innerText", errString); } ), new PositionOptions() { EnableHighAccuracy = true, Timeout = 5000, MaximumAge = 0 } ); } ) ); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); var ipcMain = await IpcMain.Create(); ipcMain.On("print-to-pdf", new IpcMainEventListener ( async(result) => { var state = result.CallbackState as object[]; var ipcMainEvent = (IpcMainEvent)state[0]; var parms = state[1] as object[]; var win = await BrowserWindow.FromWebContents(ipcMainEvent.Sender); System.Console.WriteLine($"Asynchronous message from: {await win.GetTitle()}"); // foreach (var parm in parms) // System.Console.WriteLine($"\tparm: {parm}"); var contents = await win.GetWebContents(); await contents.PrintToPDF(new PrintToPDFOptions(), new ScriptObjectCallback <Error, byte[]>( async(cr) => { await console.Log("callback in Print to Pdf"); var PDFState = cr.CallbackState as object[]; var error = PDFState[0] as Error; if (error != null) { throw new Exception(error.Message); } var buffer = PDFState[1] as byte[]; string filename = Path.GetTempFileName() + ".pdf"; File.WriteAllBytes(filename, buffer); var process = Process.Start(filename); await ipcMainEvent.Sender.Send("wrote-pdf", filename); } ) ); } ) ); } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { // Since we are executing from the Renderer process we have to use // dialog remote process. dialog = await Dialog.Instance(); var page = new HtmlPage(); document = await page.GetDocument(); // Get the HtmlElement with the id of "openFile" var openFile = await document.GetElementById("openFile"); // Attach a "click" event handler to the openFile HtmlElement await openFile.AttachEvent("click", new EventHandler(async(sender, evt) => { // Create an OpenDialogOptions reference with custom FileFilters var openOptions = new OpenDialogOptions() { Filters = new FileFilter[] { new FileFilter() { Name = "text", Extensions = new string[] { "txt" } }, new FileFilter() { Name = "All Files", Extensions = new string[] { "*" } } } }; // Now show the open dialog passing in the options created previously // and a call back function when a file is selected. // If a call back function is not specified then the ShowOpenDialog function // will return an array of the selected file(s) or an empty array if no // files are selected. await dialog.ShowOpenDialog( openOptions, openFileCallback ); } )); // Get the HtmlElement with the id of "saveFile" var saveFile = await document.GetElementById("saveFile"); // Attach a "click" event handler to the saveFile HtmlElement await saveFile.AttachEvent("click", new EventHandler(async(sender, evt) => { // Create an OpenDialogOptions reference with custom FileFilters var saveOptions = new SaveDialogOptions() { Filters = new FileFilter[] { new FileFilter() { Name = "text", Extensions = new string[] { "txt" } }, new FileFilter() { Name = "All Files", Extensions = new string[] { "*" } } } }; // Now show the save dialog passing in the options created previously // and a call back function to be called when the save button is clicked. // If a call back function is not specified then the ShowSaveDialog function // will return a string or an empty string if no file was specified. await dialog.ShowSaveDialog( saveOptions, saveFileCallback ); } )); } catch (Exception exc) { await dialog.ShowErrorBox("There was an error: ", exc.Message); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { // Create the browser window. mainWindow = await BrowserWindow.Create(new BrowserWindowOptions() { Width = 600, Height = 400 }); // and load the index.html of the app. await mainWindow.LoadURL($"file://{__dirname}/index.html"); await mainWindow.GetWebContents().ContinueWith( (t) => { var webContents = t.Result; // Subscribe to the "context-menu" event on the WebContents webContents?.On("context-menu", async(cmevt) => { // if we have not created the menu then do it now if (menu == null) { menu = await Menu.Create(); await menu.Append(await MenuItem.Create(new MenuItemOptions() { Label = "Hello", Click = MenuItemClicked })); await menu.Append(await MenuItem.Create(new MenuItemOptions() { Type = MenuItemType.Separator })); await menu.Append(await MenuItem.Create( new MenuItemOptions() { Label = "View", SubMenuOptions = new MenuItemOptions[] { new MenuItemOptions() { Role = MenuItemRole.Reload }, new MenuItemOptions() { Role = MenuItemRole.ToggleDevTools }, new MenuItemOptions() { Type = MenuItemType.Separator }, new MenuItemOptions() { Role = MenuItemRole.ResetZoom }, new MenuItemOptions() { Role = MenuItemRole.ZoomIn }, new MenuItemOptions() { Role = MenuItemRole.ZoomOut }, new MenuItemOptions() { Type = MenuItemType.Separator }, new MenuItemOptions() { Role = MenuItemRole.ToggleFullScreen }, } } )); await menu.Append(await MenuItem.Create(new MenuItemOptions() { Type = MenuItemType.Separator })); await menu.Append(await MenuItem.Create(new MenuItemOptions() { Label = "WebSharp", Type = MenuItemType.Checkbox, Checked = true, Click = MenuItemClicked })); } // popup our menu here menu.Popup(); return(null); }); // Open the DevTools webContents?.OpenDevTools(DevToolsMode.Bottom); } ); // Emitted when the window is closed. await mainWindow.On("closed", async (evt) => { await console.Log("Received closed event"); System.Console.WriteLine("Received closed event"); mainWindow = null; return(null); }); await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(await mainWindow.GetId()); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); HtmlElement dragged = null; // events fired on the draggable target */ await document.AttachEvent(HtmlEventNames.Drag, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { } ) ); await document.AttachEvent(HtmlEventNames.DragStart, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // store a ref. on the dragged element dragged = evt.Target as HtmlElement; // make it half transparent await dragged.SetStyleAttribute("opacity", ".5"); } ) ); await document.AttachEvent(HtmlEventNames.DragEnd, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // reset the transparency await evt.Target.SetStyleAttribute("opacity", ""); } ) ); await document.AttachEvent(HtmlEventNames.DragExit, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // reset the transparency await evt.Target.SetStyleAttribute("opacity", ""); } ) ); // Events fired on the drop targets await document.AttachEvent(HtmlEventNames.DragOver, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // prevent default to allow drop evt.PreventDefault(); evt.StopPropagation(); // A DropEffect must be set evt.DataTransfer.DropEffect = DropEffect.Link; } ) ); //Events fired on the drop targets await document.AttachEvent(HtmlEventNames.DragEnter, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // highlight potential drop target when the draggable element enters it if (await evt.Target.GetCssClass() == "dropzone") { await evt.Target.SetStyleAttribute("background", "purple"); } } ) ); await document.AttachEvent(HtmlEventNames.DragLeave, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // highlight potential drop target when the draggable element enters it if (await evt.Target.GetCssClass() == "dropzone") { await evt.Target.SetStyleAttribute("background", ""); } } ) ); await document.AttachEvent(HtmlEventNames.Drop, new EventHandler <HtmlEventArgs> ( async(sender, evt) => { // prevent default to allow drop evt.PreventDefault(); evt.StopPropagation(); // move dragged elem to the selected drop target if (await evt.Target.GetCssClass() == "dropzone") { await evt.Target.SetStyleAttribute("background", ""); await dragged.GetParent().ContinueWith( (t) => { t.Result?.RemoveChild(dragged); } ); //dragged.parentNode.removeChild( dragged ); await evt.Target.AppendChild(dragged); } } ) ); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var clipboard = await Clipboard.Instance(); await console.Log("Available Formats"); var formats = await clipboard.AvailableFormats(); for (int f = 0; f < formats.Length; f++) { await console.Log(formats[f]); } // if we have an image format on the clipboard the we need to readit and set the image's // source element. if (formats.Length == 1 && formats[0] == "image/png") { // Read the clipboard Image var image = await clipboard.ReadImage(); // If we have the image if (image != null) { // Get access to the DOM var page = new HtmlPage(); var document = await page.GetDocument(); // Get a reference to the img element var imageElement = await document.GetElementById("image"); if (imageElement != null) { // set the src property to the data string of the image/ await imageElement.SetProperty("src", await image.ToDataURL()); } } } await clipboard.WriteText("Example String copied to clipboard"); await console.Log($"Clipboard text read: {await clipboard.ReadText()}"); await console.Log("Clearing clipboard"); await clipboard.Clear(); await console.Log("Available Formats"); formats = await clipboard.AvailableFormats(ClipboardType.Selection); for (int f = 0; f < formats.Length; f++) { await console.Log(formats[f]); } await console.Log("Writing data to the clipboard"); await clipboard.Write(new ClipboardData() { Text = "test", HTML = "<b>test</b>" }); await console.Log("Available Formats"); formats = await clipboard.AvailableFormats(ClipboardType.Selection); for (int f = 0; f < formats.Length; f++) { await console.Log(formats[f]); } await console.Log($"Reading Clipboard Text data: {await clipboard.ReadText()}"); await console.Log($"Reading Clipboard HTML data: {await clipboard.ReadHTML()}"); await console.Log($"Reading Clipboard RTF data: {await clipboard.ReadRTF()}"); await console.Log($"Has {await clipboard.Has("<p>selection</p>")}"); await console.Log("Writing bookmark to the clipboard"); await clipboard.WriteBookmark("Electron Homepage", @"https://electron.atom.io"); await console.Log(await clipboard.ReadBookmark()); await console.Log("Available Formats"); formats = await clipboard.AvailableFormats(ClipboardType.Selection); for (int f = 0; f < formats.Length; f++) { await console.Log(formats[f]); } await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var document = await HtmlPage.GetDocument(); var findMe = await document.GetElementById("findMe"); var map = await document.GetElementById("map"); var location = await document.GetElementById("location"); var error = false; await findMe.AttachEvent("click", new EventHandler( async(sender, evt) => { error = false; await location.SetProperty("innerText", "Locating ..."); var geo = await GeoLocationAPI.Instance(); await geo.GetCurrentPosition( new ScriptObjectCallback <GeoPosition>( async(cr) => { var position = cr.CallbackState as GeoPosition; var coords = position.Coordinates; var posString = $"Your current position is:\nLatitude : {coords.Latitude}\nLongitude : {coords.Longitude}\nMore or less {coords.Accuracy} Meters."; await location.SetProperty("innerText", posString); var imageURL = $"https://maps.googleapis.com/maps/api/staticmap?center={coords.Latitude},{coords.Longitude}&zoom=13&size=300x300&sensor=false"; await map.SetProperty("src", imageURL); } ), new ScriptObjectCallback <PositionError>( async(cr) => { var err = cr.CallbackState as PositionError; var errString = $"ERROR({err.ErrorCode}): {err.Message}"; if (error) { var errorText = await location.GetProperty <string>("innerText"); errString = $"{errorText}\n{errString}"; } error = true; await location.SetProperty("innerText", errString); } ), new PositionOptions() { EnableHighAccuracy = true, Timeout = 5000, MaximumAge = 0 } ); } ) ); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { var mediaStuff = await WebSharpJs.WebSharp.CreateJavaScriptFunction( @" return function (data, callback) { console.log('mediadevice id --------:' + data); navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: data, minWidth: 640, maxWidth: 640, minHeight: 360, maxHeight: 360 } } }).then(handleStream).catch(handleError); function handleStream (stream) { console.log('handle stream'); document.querySelector('video').src = URL.createObjectURL(stream) } function handleError (e) { console.log(e) } callback(null, null); }"); var desktopCapturer = await DesktopCapturer.Instance(); // GetSources - Starts gathering information about all available desktop media sources, and calls // ScriptObjectCallback<Error, DesktopCapturerSource[]> when finished. await desktopCapturer.GetSources(new DesktopCapturerOptions() { Types = DesktopCapturerType.Window | DesktopCapturerType.Screen }, new ScriptObjectCallback <Error, DesktopCapturerSource[]>( async(result) => { var resultState = (object[])result.CallbackState; var error = resultState[0] as Error; var sources = resultState[1] as DesktopCapturerSource[]; if (error != null) { throw new Exception(error.Message); } if (sources == null) { return; } // Loop through all available sources. foreach (var source in sources) { // Log the sources and their thumbnail sizes. await console.Log($"source id: {source.Id} name: {source.Name} size: {await source.Thumbnail.GetSize()}"); // Grab the "Entire screen" id if (source.Name == "Entire screen") { // Pass the source id. await mediaStuff(source.Id); } } })); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); // Get our session try { session = await Session.FromPartition("partition:nameofpartition"); } catch (Exception sexc) { await console.Log($"logging: {sexc.Message}"); var web = await mainWindow.GetWebContents(); session = await web.GetSession(); } if (session != null) { await session.SetPermissionRequestHandler( new ScriptObjectCallback <WebContents, string, Func <object, Task <object> > >( async(callbackResult) => { var permissionResult = new PermissionRequestResult(callbackResult); var url = await permissionResult.WebContents.GetURL(); await console.Log($"Received permission request from {url} for access to \"{permissionResult.Permission}\"."); if (permissionResult.Permission == Permission.PointerLock) { permissionResult.Callback(await GrantAccess(permissionResult.Permission)); } else { permissionResult.Callback(true); } } ) ); } } await console.Log($"Loading: file://{__dirname}/index.html"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="__dirname">The directory name of the current module. This the same as the path.dirname() of the __filename.</param> /// <returns></returns> public async Task <object> Invoke(string __dirname) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { app = await App.Instance(); // We use app.IsReady instead of listening for the 'ready'event. // By the time we get here from the main.js module the 'ready' event has // already fired. if (await app.IsReady()) { windowId = await CreateWindow(__dirname); } await console.Log($"Loading: file://{__dirname}/index.html"); // Note: Sending a synchronous message from the render process will block // the whole renderer process, unless you know what you are doing you should never use it. // // We will define the synchronous function via a javascript function // There is a limitation on synchronous messages via the CLR because of the // event.returnValue will not be set via the CLR. // If synchronous messaging is desired then a CLR implementation is what // you want. var synchronousFunction = await WebSharpJs.WebSharp.CreateJavaScriptFunction( @" return function (data, callback) { const {ipcMain} = require('electron') ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // prints 'ping' event.returnValue = 'synchronous pong' }); callback(null, null); }"); await synchronousFunction(null); // attach our synchronous message listener IpcMain ipcMain = await IpcMain.Create(); ipcMain.On("asynchronous-message", new IpcMainEventListener ( async(result) => { var state = result.CallbackState as object[]; var ipcMainEvent = (IpcMainEvent)state[0]; var parms = state[1] as object[]; System.Console.WriteLine($"Asynchronous message from: {await ipcMainEvent.Sender.GetTitle()}"); foreach (var parm in parms) { System.Console.WriteLine($"\tparm: {parm}"); } await ipcMainEvent.Sender.Send("asynchronous-reply", "asynchronous-pong1", "asynchronous-pong2"); } ) ); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(windowId); }
/// <summary> /// Default entry into managed code. /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <object> Invoke(object input) { if (console == null) { console = await WebSharpJs.NodeJS.Console.Instance(); } try { ipcRenderer = await IpcRenderer.Create(); document = await HtmlPage.GetDocument(); var form = await document.QuerySelector("form"); // Input fields source = await form.QuerySelector("input[name=\"source\"]"); destination = await form.QuerySelector("input[name=\"destination\"]"); name = await form.QuerySelector("input[name=\"name\"]"); // Buttons btnSource = await document.GetElementById("chooseSource"); btnDestination = await document.GetElementById("chooseDestination"); btnSubmit = await form.QuerySelector("button[type=\"submit\"]"); // Handle input fields await source.AttachEvent(HtmlEventNames.Input, updateUI); await source.AttachEvent(HtmlEventNames.Change, updateUI); await destination.AttachEvent(HtmlEventNames.Input, updateUI); await destination.AttachEvent(HtmlEventNames.Change, updateUI); await name.AttachEvent(HtmlEventNames.Input, updateUI); // Handle buttons await btnSource.AttachEvent(HtmlEventNames.Click, handleSource); await btnDestination.AttachEvent(HtmlEventNames.Click, handleDestination); // Handle form Submit await form.AttachEvent(HtmlEventNames.Submit, async (s, e) => { e.PreventDefault(); await ToggleUI(true); // Send off the convert request await ipcRenderer.Send("submitform", await source.GetProperty <string>("value"), await destination.GetProperty <string>("value"), await name.GetProperty <string>("value") ); } ); await ipcRenderer.AddListener("gotMetaData", new IpcRendererEventListener( async(result) => { var state = result.CallbackState as object[]; var ipcMainEvent = (IpcRendererEvent)state[0]; var parms = state[1] as object[]; var audio = ScriptObjectHelper.AnonymousObjectToScriptableType <Audio>(parms[0]); var video = ScriptObjectHelper.AnonymousObjectToScriptableType <Video>(parms[1]); var duration = TimeSpan.Parse(parms[2].ToString()); await updateInfo(audio, video, duration); } ) ); await ipcRenderer.AddListener("completed", new IpcRendererEventListener( async(result) => { await ToggleUI(false); } ) ); await console.Log($"Hello: {input}"); } catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); } return(null); }