private static async Task CreatePromiseAsync(IJsObject window) { //It is also possible to create a wrapper class for IJsObject that simplifies appending the //handlers and type checks. Such approach can be used to integrate JavaScript promises //with async/await in the .NET application. //Create a promise that is fulfilled and wrap this promise Console.WriteLine("\nCreate another promise that is fulfilled..."); JsPromise promise3 = window.Invoke <IJsObject>("CreatePromise", true).AsPromise(); JsPromise.Result result = await promise3.Then(o => { Console.WriteLine($"Callback:Success: {o}"); return(o); }) .ResolveAsync(); Console.WriteLine($"Result state:{result?.State}"); Console.WriteLine($"Result type:{(result?.Data?.GetType().ToString() ?? "null")}"); //Create a promise that is rejected and wrap this promise Console.WriteLine("\nCreate another promise that is rejected..."); JsPromise promise4 = window.Invoke <IJsObject>("CreatePromise", false).AsPromise(); result = await promise4.ResolveAsync(); Console.WriteLine($"Result state:{result?.State}"); Console.WriteLine($"Result type:{(result?.Data?.GetType().ToString() ?? "null")}"); }
public OwnedValuePropertyDescriptor(IJsObject owner, string name, IJsValue value, PropertyDescriptorFlags flags) { Owner = owner; Name = name; Value = value; Flags = flags; }
public static void Main() { using (IEngine engine = EngineFactory.Create()) { using (IBrowser browser = engine.CreateBrowser()) { IJsObject document = browser.MainFrame .ExecuteJavaScript <IJsObject>("document") .Result; // document.title = "New Title" document.Properties["title"] = "New Title"; // document.write("Hello World!") document.Invoke("write", "Hello World!"); string documentContent = browser.MainFrame .ExecuteJavaScript <string>("document.body.innerText") .Result; Console.Out.WriteLine($"New content: {documentContent}"); } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
/// <summary> /// Constructor used for outgoing codepaths /// </summary> /// <param name="client"></param> /// <param name="name"></param> /// <param name="id"></param> /// <param name="obj"></param> private ObjectEntry(SharedObjectsClient client, string name, Guid id, INotifyPropertyChanged obj) { this.client = client; this.IgnoreChanges = false; this.Object = obj; this.Id = id; this.Name = name ?? this.Id.ToString(); IJsObject jsObj = obj as IJsObject; // do this here so we only do the cast once this.IsDynamic = jsObj != null; this.Parents = new Dictionary <Guid, ParentEntry>(); this.Type = obj.GetType(); this.Attributes = new SharedAttributes(obj.GetType()); if (jsObj != null) { this.Properties = new SharedPropertyDictionary(jsObj.GetSharedProperties(this.client.ClientId)); } else { this.Properties = new SharedPropertyDictionary(obj.GetSharedProperties(this.client.ClientId)); } }
public static void Main() { try { using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder().Build())) { Console.WriteLine("Engine created"); using (IBrowser browser = engine.CreateBrowser()) { Console.WriteLine("Browser created"); IJsObject document = browser.MainFrame.ExecuteJavaScript <IJsObject>("document").Result; // document.title = "New Title" document.Properties["title"] = "New Title"; // document.write("Hello World!") document.Invoke("write", "Hello World!"); string documentContent = browser.MainFrame.ExecuteJavaScript <string>("document.body.innerText").Result; Console.Out.WriteLine("New content: " + documentContent); } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private static void Main(string[] args) { try { using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder().Build())) { Console.WriteLine("Engine created"); using (IBrowser browser = engine.CreateBrowser()) { Console.WriteLine("Browser created"); IJsObject arrayObject = browser.MainFrame .ExecuteJavaScript <IJsObject>(JsArray) .Result; JsArray array = arrayObject.AsArray(); if (array != null) { Console.Out.WriteLine("Item count: " + array.Count); foreach (object item in array) { Console.Out.WriteLine("Item: " + item); } } } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private static void Main(string[] args) { using (IEngine engine = EngineFactory.Create()) { using (IBrowser browser = engine.CreateBrowser()) { IJsObject arrayObject = browser.MainFrame .ExecuteJavaScript <IJsObject>(JsArray) .Result; JsArray array = arrayObject.AsArray(); if (array != null) { Console.Out.WriteLine($"Item count: {array.Count}"); foreach (object item in array) { Console.Out.WriteLine($"Item: {item}"); } } } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private void OnPovChanged() { IJsObject jsPov = panorama.Invoke <IJsObject>("getPov"); pov = new Pov(jsPov.Properties["heading"], jsPov.Properties["pitch"]); PovChanged?.Invoke(this, EventArgs.Empty); }
public StreetViewPanorama(IJsObject jsPanorama) { panorama = jsPanorama; AddListener("pano_changed", OnPanoramaChanged); AddListener("pov_changed", OnPovChanged); AddListener("position_changed", OnPositionChanged); }
private void OnInjectJs(InjectJsParameters parameters) { //Inject window.external into the HTML page IJsObject window = parameters.Frame.ExecuteJavaScript <IJsObject>("window").Result; window.Properties["external"] = this; }
private void button1_Click(object sender, EventArgs e) { IJsObject textElement = browser.MainFrame.ExecuteJavaScript <IJsObject>("document.getElementById('text');") .Result; textElement.Properties["value"] = richTextBox1.Text; }
public static void Main() { try { using (IEngine engine = EngineFactory.Create()) { Console.WriteLine("Engine created"); using (IBrowser browser = engine.CreateBrowser()) { Console.WriteLine("Browser created"); browser.Size = new Size(700, 500); browser.MainFrame.LoadHtml(@"<html> <body> <script type='text/javascript'> function CreatePromise(success) { return new Promise(function(resolve, reject) { if(success) { resolve('Promise fulfilled.'); } else { reject('Promise rejected.'); } }); }; </script> </body> </html>") .Wait(); IJsObject window = browser.MainFrame.ExecuteJavaScript <IJsObject>("window").Result; //Prepare promise handlers Action <object> promiseResolvedHandler = o => Console.WriteLine("Success: " + o); Action <object> promiseRejectedHandler = o => Console.Error.WriteLine("Error: " + o); //Create a promise that is fulfilled Console.WriteLine("Create a promise that is fulfilled..."); IJsObject promise1 = window.Invoke <IJsObject>("CreatePromise", true); //Append fulfillment and rejection handlers to the promise promise1.Invoke("then", promiseResolvedHandler, promiseRejectedHandler); //Create a promise that is rejected Console.WriteLine("Create a promise that is rejected..."); IJsObject promise2 = window.Invoke <IJsObject>("CreatePromise", false); //Append fulfillment and rejection handlers to the promise promise2.Invoke("then", promiseResolvedHandler, promiseRejectedHandler); CreatePromiseAsync(window).Wait(); } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private static void Main(string[] args) { try { Size browserSize = new Size(500, 500); using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder { RenderingMode = RenderingMode.OffScreen, ChromiumSwitches = { "--allow-file-access-from-files" } }.Build())) { Console.WriteLine("Engine created"); using (IBrowser browser = engine.CreateBrowser()) { // 1. Resize browser to the required dimension. browser.Size = browserSize; // 2. Load the required web page and wait until it is loaded completely. browser.Navigation.LoadUrl(Path.GetFullPath("sample.html")).Wait(); // 3. Create canvas, set its width and height IJsObject canvas = browser .MainFrame.ExecuteJavaScript <IJsObject>("document.createElement('canvas');") .Result; IElement image = browser.MainFrame.Document.GetElementByTagName("img"); string width = image.Attributes["width"]; canvas.Properties["width"] = width; string height = image.Attributes["height"]; canvas.Properties["height"] = height; // 4. Get the canvas context and draw the image on it IJsObject ctx = canvas.Invoke("getContext", "2d") as IJsObject; ctx.Invoke("drawImage", image, 0, 0); // 5. Get the data URL and convert it to bytes string dataUrl = canvas.Invoke("toDataURL", "image/png") as string; Console.WriteLine("Data URL: " + dataUrl); byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage(dataUrl)); // 4. Save image to file. using (FileStream fs = new FileStream("image.png", FileMode.Create, FileAccess.Write)) { fs.Write(bitmapData, 0, bitmapData.Length); } Console.WriteLine("Image saved."); } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private static void OnInjectJs(InjectJsParameters parameters) { IJsObject window = parameters.Frame.ExecuteJavaScript <IJsObject>("window").Result; window.Properties["notificationCallback"] = notificationCallback; parameters.Frame.ExecuteJavaScript(InjectedScript); }
private static void OnInjectJs(InjectJsParameters parameters) { IJsObject window = parameters.Frame.ExecuteJavaScript <IJsObject>("window").Result; window.Properties["websocketCallback"] = webSocketCallback; parameters.Frame.ExecuteJavaScript(JavaScript); }
public static void Main() { using (IEngine engine = EngineFactory.Create()) { using (IBrowser browser = engine.CreateBrowser()) { browser.Size = new Size(700, 500); byte[] htmlBytes = Encoding.UTF8.GetBytes(@"<html> <body> <script type='text/javascript'> function CreatePromise(success) { return new Promise(function(resolve, reject) { if(success) { resolve('Promise fulfilled.'); } else { reject('Promise rejected.'); } }); }; </script> </body> </html>"); browser.Navigation .LoadUrl($"data:text/html;base64,{Convert.ToBase64String(htmlBytes)}") .Wait(); IJsObject window = browser.MainFrame .ExecuteJavaScript <IJsObject>("window") .Result; //Prepare promise handlers Action <object> promiseResolvedHandler = o => Console.WriteLine($"Success: {o}"); Action <object> promiseRejectedHandler = o => Console.Error.WriteLine($"Error: {o}"); //Create a promise that is fulfilled Console.WriteLine("Create a promise that is fulfilled..."); IJsObject promise1 = window.Invoke <IJsObject>("CreatePromise", true); //Append fulfillment and rejection handlers to the promise promise1.Invoke("then", promiseResolvedHandler, promiseRejectedHandler); //Create a promise that is rejected Console.WriteLine("Create a promise that is rejected..."); IJsObject promise2 = window.Invoke <IJsObject>("CreatePromise", false); //Append fulfillment and rejection handlers to the promise promise2.Invoke("then", promiseResolvedHandler, promiseRejectedHandler); CreatePromiseAsync(window).Wait(); } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private void OnPositionChanged() { IJsObject jsPosition = panorama.Invoke <IJsObject>("getPosition"); double latitude = jsPosition.Invoke <double>("lat"); double longitude = jsPosition.Invoke <double>("lng"); position = new LatLng(latitude, longitude); PositionChanged?.Invoke(this, EventArgs.Empty); }
//JS-.NET callback public void OnPanoramaInitialized(IJsObject jsPanorama) { //Create a wrapper for StreetViewPanorama and subscribe to the events //to update the form properly. panorama = new StreetViewPanorama(jsPanorama); panorama.PanoChanged += OnPanoChanged; panorama.PovChanged += OnPovChanged; panorama.PositionChanged += OnPositionChanged; }
private static bool IsArray(IJsObject jsObject) { if (jsObject == null || jsObject.IsDisposed) { return(false); } IJsFunction isArrayFunction = jsObject.Frame.ExecuteJavaScript <IJsFunction>("Array.isArray").Result; return(isArrayFunction.Invoke <bool>(null, jsObject)); }
private static bool IsPromise(IJsObject jsObject) { if (jsObject == null || jsObject.IsDisposed) { return(false); } IJsObject promisePrototype = jsObject.Frame.ExecuteJavaScript <IJsObject>("Promise.prototype").Result; return(promisePrototype.Invoke <bool>("isPrototypeOf", jsObject)); }
public static void Main() { try { LoggerProvider.Instance.Level = SourceLevels.Information; LoggerProvider.Instance.FileLoggingEnabled = true; LoggerProvider.Instance.OutputFile = "dnb.log"; using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder().Build())) { Console.WriteLine("Engine created"); using (IBrowser browser = engine.CreateBrowser()) { Console.WriteLine("Browser created"); browser.Size = new Size(700, 500); browser.MainFrame.LoadHtml(@"<html> <body> <script type='text/javascript'> var ShowData = function (a) { document.title = a.FullName + ' ' + a.Age + '. ' + a.Walk(a.Children.get_Item(1)) + ' ' + a.Children.get_Item(1).FullName + ' ' + a.Children.get_Item(1).Age; }; </script> </body> </html>") .Wait(); Person person = new Person("Jack", 30, true) { Children = new Dictionary <double, Person>() }; person.Children.Add(1.0, new Person("Oliver", 10, true)); IJsObject value = browser.MainFrame.ExecuteJavaScript <IJsObject>("window").Result; value.Invoke("ShowData", person); Console.WriteLine($"\tBrowser title: {browser.Title}"); } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
static void TestScripting(Assembly asm, string[] args) { //Do you remember Executor brings some possibilities? Let's explore those. Executor exe = new Executor(asm); exe.ResolveExternalLibrary += Executor.DefaultExternalLibraryResolver; exe.Execute(args); //Executing JS code from C# is one of them. Func <string, object> parseArg = exe.ExternalVariables.GetFunc <string, object>("parseArg"); object parsedArgRaw = parseArg("ex=sf56"); IJsObject parsedArg = Executor.BridgeJsObject(parsedArgRaw); string parsedArgValue = parsedArg.GetValue("value") as string; }
public void Drop(IJsObject data) { WriteLine("JavaScript Drop callback received: " + data); if (data.Properties.Contains("length")) { double length = (double)data.Properties["length"]; for (uint i = 0; i < length; i++) { IJsObject file = data.Properties[i] as IJsObject; if (file != null) { WriteLine($"data[{i}] = {file.Properties["name"]}"); } } } }
public static void Main() { LoggerProvider.Instance.Level = SourceLevels.Information; LoggerProvider.Instance.FileLoggingEnabled = true; LoggerProvider.Instance.OutputFile = "dnb.log"; using (IEngine engine = EngineFactory.Create()) { using (IBrowser browser = engine.CreateBrowser()) { browser.Size = new Size(700, 500); byte[] htmlBytes = Encoding.UTF8.GetBytes(@"<html> <body> <script type='text/javascript'> var ShowData = function (a) { document.title = a.FullName + ' ' + a.Age + '. ' + a.Walk(a.Children.get_Item(1)) + ' ' + a.Children.get_Item(1).FullName + ' ' + a.Children.get_Item(1).Age; }; </script> </body> </html>"); browser.Navigation .LoadUrl($"data:text/html;base64,{Convert.ToBase64String(htmlBytes)}") .Wait(); Person person = new Person("Jack", 30, true) { Children = new Dictionary <double, Person>() }; person.Children.Add(1.0, new Person("Oliver", 10, true)); IJsObject value = browser.MainFrame .ExecuteJavaScript <IJsObject>("window") .Result; value.Invoke("ShowData", person); Console.WriteLine($"\tBrowser title: {browser.Title}"); } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
public Executor(Assembly toExecute) { Type type = toExecute.GetType("Root"); _mi = type.GetMethod("Main", BindingFlags.Public | BindingFlags.Instance); _global = Activator.CreateInstance(type); _act = (Action <object[]>)Delegate.CreateDelegate(typeof(Action <object[]>), _global, _mi); //_externalVariables=type.GetProperty("ExternalVariables")?.GetValue(_global,new object[0]) as IJsObject; _externalVariables = BridgeJsObject(_global); Action <ResolveExternalLibraryEventArgs> externalLibraryResolver = new Action <ResolveExternalLibraryEventArgs>(e => { FireResolveExternalLibrary(this, e); }); FieldInfo fi = type.GetField("~externalLibraryResolver", BindingFlags.NonPublic | BindingFlags.Instance); fi.SetValue(_global, fi.FieldType.GetConstructors()[0].Invoke(new object[] { this, externalLibraryResolver.Method.MethodHandle.GetFunctionPointer() })); }
private static void Main(string[] args) { using (IEngine engine = EngineFactory.Create()) { using (IBrowser browser = engine.CreateBrowser()) { browser.Size = new Size(1024, 768); browser.Navigation.LoadUrl(Path.GetFullPath("example.html")).Wait(); Console.WriteLine("URL loaded"); IDocument document = browser.MainFrame.Document; IJsObject container = document.GetElementById("container") as IJsObject; //Create shadow root. INode shadowRoot = container?.Invoke <INode>("attachShadow", browser .MainFrame .ParseJsonString("{\"mode\": \"open\"}")); Console.WriteLine($"Shadow root created: {(shadowRoot != null)}"); //Fetch shadow root. shadowRoot = container?.Properties["shadowRoot"] as INode; Console.WriteLine($"Shadow root fetched: {(shadowRoot != null)}"); //Add node to shadow root. IElement inside = document.CreateElement("h1"); inside.InnerText = "Inside Shadow DOM"; inside.Attributes["id"] = "inside"; shadowRoot?.Children.Append(inside); //Find new node in shadow root. IElement element = shadowRoot?.GetElementById("inside"); Console.WriteLine($"Inside element inner text: {element?.InnerText}"); //Try finding the same node from the main document. element = document.GetElementById("inside"); Console.WriteLine($"Inside element found in the document: {(element != null)}"); } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
public Form1() { InitializeComponent(); BrowserView webView = new BrowserView { Dock = DockStyle.Fill }; tableLayoutPanel1.Controls.Add(webView, 1, 0); tableLayoutPanel1.SetRowSpan(webView, 2); engine = EngineFactory .Create(new EngineOptions.Builder { RenderingMode = RenderingMode.HardwareAccelerated } .Build()); browser = engine.CreateBrowser(); webView.InitializeFrom(browser); browser.ConsoleMessageReceived += (sender, args) => { }; browser .MainFrame .LoadHtml(@"<html> <head> <meta charset='UTF-8'> <style>body{padding: 0; margin: 0; width:100%; height: 100%;} textarea.fill {padding: 2; margin: 0; width:100%; height:100%;} button{position: absolute; bottom: 0; padding: 2; width:100%;}</style> </head> <body> <div> <textarea id='text' class='fill' autofocus cols='30' rows='20'>Sample text</textarea> <button id='updateForm' type='button' onClick='updateForm(document.getElementById(""text"").value)'>< Update Form</button> </div> </body> </html>") .Wait(); IJsObject window = browser.MainFrame.ExecuteJavaScript <IJsObject>("window").Result; window.Properties["updateForm"] = (Action <string>)UpdateForm; FormClosing += Form1_FormClosing; }
private void ConfigureObserver() { // Inject the listener .NET object into Javascript IJsObject window = browser.MainFrame.ExecuteJavaScript <IJsObject>("window").Result; window.Properties["MutationObserverListener"] = this; // The script for configuring MutationObserver to observe the changes of // the element with id 'countdown'. string observerScript = "var spanElement = document.getElementById('countdown');" + "var observer = new MutationObserver(" + "function(mutations){" + "window.MutationObserverListener.CharacterDataChanged(spanElement.innerHTML);" + "});" + "var config = { childList: true };" + "observer.observe(spanElement, config);"; // Execute the script that configures the observer. // After the observer is configured, the .NET side starts receiving element changes. browser.MainFrame.ExecuteJavaScript(observerScript); }
/// <summary> /// Extension method to serialize the key value pairs in a dictionary. /// </summary> /// <param name="obj">A Dictionary</param> /// <returns>Returns a Dictionary of serialized SharedProperty values</returns> public static Dictionary <short, SharedProperty> GetSharedProperties(this IJsObject obj, Guid clientId) { // TODO: Need to investigate adding attributes to the shared dictionary properties var sharedProps = new Dictionary <short, SharedProperty>(); short curIndex = 0; // Explicitly casting the obj to IDictionary<string, object> because of a warning regarding the ambiguity between // IDictionary.GetEnumerator() and IDictionary<string, object).GetEnumerator(). foreach (KeyValuePair <string, object> kv in (IDictionary <string, object>)obj) { sharedProps.Add(curIndex, new SharedProperty() { Name = kv.Key, Value = Json.WriteObject(kv.Value), Index = curIndex, ETag = new ETag(clientId), Attributes = new SharedAttributes(), PropertyType = DynamicTypeMapping.Instance.GetValueFromType(kv.Value.GetType()) }); ++curIndex; } return(sharedProps); }
/// <summary> /// Update the properties of the target object with the contents of the ObjectPayload /// </summary> /// <param name="target"></param> /// <param name="data"></param> private void UpdateProperties(INotifyPropertyChanged target, ObjectPayload data) { this.client.VerifyAccess(); Type targetType = target.GetType(); IJsObject jsDictionary = target as IJsObject; if (jsDictionary != null) { // In case of JsObservableDictionary, we want to treat the properties in this payload as items of the dictionary foreach (SharedProperty sharedProp in data.SharedProperties.Values) { jsDictionary[sharedProp.Name] = Json.ReadObject(DynamicTypeMapping.Instance.GetTypeFromValue(sharedProp.PropertyType), sharedProp.Value); } } else { foreach (SharedProperty sharedProp in data.SharedProperties.Values) { Json.AssignProperty(target, sharedProp.Name, sharedProp.Value); } } }
public OwnedValuePropertyDescriptor(IJsObject owner, string name) : this(owner, name, JsUndefined.Value, PropertyDescriptorFlags.Enumerable | PropertyDescriptorFlags.Writable | PropertyDescriptorFlags.Configurable) { }
public JsObjectDebugView(IJsObject container) { _container = container; }
public JsClass(Dictionary<string,IPropertyDescriptor> instanceProperties, IJsObject prototype) { _instanceProperties = instanceProperties; Prototype = prototype; }