public static string EvaluateScript(this GeckoWebBrowser browser, string jsString)
 {
     using (var autoJSContext = new AutoJSContext(browser.Window.JSContext))
     {
         var jsVal = autoJSContext.EvaluateScript(jsString, browser.Window.DomWindow);
         return jsVal.ToString();
     }
 }
		public void JS_TypeOfValue()
		{
			if (Xpcom.IsLinux && IntPtr.Size == 8)
				Assert.Ignore("unsafe test:seg faults on 64bit Linux");

			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{
				Assert.AreEqual(JSType.JSTYPE_NUMBER, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, JsVal.FromPtr(0)));
				Assert.AreEqual(JSType.JSTYPE_NUMBER, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, JsVal.FromPtr(0xffff0000ffffffff)));
				Assert.AreEqual(JSType.JSTYPE_BOOLEAN, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, JsVal.FromPtr(0xffffffffffffffff)));
			}
		}
Exemplo n.º 3
0
		public JSAutoCompartment(AutoJSContext context, nsISupports comObject)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.ContextPointer == IntPtr.Zero)
				throw new ArgumentException("context has Null ContextPointer");
			if (context == null)
				throw new ArgumentNullException("comObject");

			_obj = context.ConvertCOMObjectToJSObject(comObject);
			_cx = context.ContextPointer;
			_oldCompartment = SpiderMonkey.JS_EnterCompartment(_cx, _obj);			
		}
		/// <summary>
		/// Unittest helper method to create a String JsVal
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		private static JsVal CreateJsVal(string jscript)
		{
			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{				
				var ptr = new JsVal();
				var _securityManager = Xpcom.GetService<nsIScriptSecurityManager>("@mozilla.org/scriptsecuritymanager;1");
				var _systemPrincipal = _securityManager.GetSystemPrincipal();

				IntPtr globalObject = SpiderMonkey.JS_GetGlobalForScopeChain(cx.ContextPointer);
				bool ret = SpiderMonkey.JS_EvaluateScript(cx.ContextPointer, globalObject, jscript, (uint)jscript.Length, "script", 1, ref ptr);
				Assert.IsTrue(ret);
				Marshal.ReleaseComObject(_securityManager);

				return ptr;
			}
		}
Exemplo n.º 5
0
        /// <summary>
        /// Get byte array with png image of the current browsers Window.
        /// Wpf methods on windows platform don't use a Bitmap :-/
        /// Not captures plugin (Flash,etc...) windows
        /// </summary>
        /// <param name="xOffset"></param>
        /// <param name="yOffset"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static byte[] CanvasGetPngImage(IGeckoWebBrowser browser, uint xOffset, uint yOffset, uint width, uint height)
        {
            if (width == 0)
                throw new ArgumentException("width");

            if (height == 0)
                throw new ArgumentException("height");

            // Use of the canvas technique was inspired by: the abduction! firefox plugin by Rowan Lewis
            // https://addons.mozilla.org/en-US/firefox/addon/abduction/

            // Some opertations fail without a proper JSContext.
            using (AutoJSContext jsContext = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
            {
                GeckoCanvasElement canvas = (GeckoCanvasElement)browser.Document.CreateElement("canvas");
                canvas.Width = width;
                canvas.Height = height;

                nsIDOMHTMLCanvasElement canvasPtr = (nsIDOMHTMLCanvasElement)canvas.DomObject;
                nsIDOMCanvasRenderingContext2D context;
                using (nsAString str = new nsAString("2d"))
                {
                    context = (nsIDOMCanvasRenderingContext2D)canvasPtr.MozGetIPCContext(str);
                }

                // the bitmap image needs to conform to the (Full)Zoom being applied, otherwise it will render wrongly
                var zoom = browser.GetMarkupDocumentViewer().GetFullZoomAttribute();
                context.Scale(zoom, zoom);

                using (nsAString color = new nsAString("rgb(255,255,255)"))
                {
                    context.DrawWindow((nsIDOMWindow)browser.Window.DomWindow, xOffset, yOffset, width, height, color,
                                        (uint)(nsIDOMCanvasRenderingContext2DConsts.DRAWWINDOW_DO_NOT_FLUSH |
                                                   nsIDOMCanvasRenderingContext2DConsts.DRAWWINDOW_DRAW_VIEW |
                                                   nsIDOMCanvasRenderingContext2DConsts.DRAWWINDOW_ASYNC_DECODE_IMAGES |
                                                   nsIDOMCanvasRenderingContext2DConsts.DRAWWINDOW_USE_WIDGET_LAYERS));
                    ;
                }

                string data = canvas.toDataURL("image/png");
                byte[] bytes = Convert.FromBase64String(data.Substring("data:image/png;base64,".Length));
                return bytes;
            }
        }
Exemplo n.º 6
0
        public string JSCall(string script)
        {
            string outString = "";

            using (var js = new Gecko.AutoJSContext(browser.Window.JSContext))
            {
                try
                {
                    js.EvaluateScript(script, (nsISupports)browser.Window.DomWindow, out outString);
                }
                catch (GeckoJavaScriptException ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
                catch (System.NotImplementedException ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
            }
            return(outString);
        }
Exemplo n.º 7
0
            /// <summary>
            /// Inserts a rule at the specified position in the collection.  The return value is the index in the list where the item was actually inserted,
            /// or -1 if the rule contains syntax errors and could not be added to the collection.
            /// </summary>
            /// <param name="index"></param>
            /// <param name="rule"></param>
            public int Insert(int index, string rule)
            {
                if (IsReadOnly)
                {
                    throw new InvalidOperationException("This collection is read-only.");
                }
                else if (index < 0 || index > Count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }
                else if (string.IsNullOrEmpty(rule))
                {
                    return(-1);
                }

                using (AutoJSContext context = new AutoJSContext(GetJSContext()))
                {
                    context.PushCompartmentScope((nsISupports)StyleSheet._DomStyleSheet);
                    var val = context.EvaluateScriptBypassingSomeSecurityRestrictions(String.Format("this.insertRule('{0}',{1});", rule, index));
                    return(val.ToInteger());
                }

                return(index);
            }
Exemplo n.º 8
0
        /// <summary>
        /// Converts to COM object without null check
        /// </summary>
        /// <param name="cx"></param>
        /// <returns></returns>
        private object ToComObjectInternal(IntPtr cx)
        {
            using (var context = new AutoJSContext(cx))
            {
                var jsObject = SpiderMonkey.JS_ValueToObject(context.ContextPointer, this);

                var guid = typeof(nsISupports).GUID;
                var pUnk = IntPtr.Zero;
                try
                {
                    pUnk = Xpcom.XPConnect.Instance.WrapJS(context.ContextPointer, jsObject, ref guid);
                    var comObj = Xpcom.GetObjectForIUnknown(pUnk);

                    return(comObj);
                }
                finally
                {
                    if (pUnk != IntPtr.Zero)
                    {
                        Marshal.Release(pUnk);
                    }
                }
            }
        }
Exemplo n.º 9
0
            /// <summary>
            /// Inserts a rule at the specified position in the collection.  The return value is the index in the list where the item was actually inserted,
            /// or -1 if the rule contains syntax errors and could not be added to the collection.
            /// </summary>
            /// <param name="index"></param>
            /// <param name="rule"></param>
            public int Insert(int index, string rule)
            {
                if (IsReadOnly)
                {
                    throw new InvalidOperationException("This collection is read-only.");
                }
                else if (index < 0 || index > Count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }
                else if (string.IsNullOrEmpty(rule))
                {
                    return(-1);
                }

                const int NS_ERROR_DOM_SYNTAX_ERR = unchecked ((int)0x8053000c);

                using (AutoJSContext context = new AutoJSContext(GetJSContext()))
                {
                    index = (int)StyleSheet._DomStyleSheet.InsertRule(new nsAString(rule), (uint)index);
                }

                return(index);
            }
Exemplo n.º 10
0
 public override string ToString()
 {
     using (AutoJSContext context = new AutoJSContext())
     {
         IntPtr jsString = SpiderMonkey.JS_ValueToString(context.ContextPointer, this);
         return Marshal.PtrToStringAnsi(SpiderMonkey.JS_EncodeString(context.ContextPointer, jsString));
     }
 }
        void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string jsResults;
            using (var context = new AutoJSContext(_browser.Window.JSContext))
            using (new JSAutoCompartment(context, (nsISupports)_browser.Window.DomWindow))
            {
                context.EvaluateScript("(Blockly.Xml.domToPrettyText(Blockly.Xml.workspaceToDom(Blockly.mainWorkspace)))", out jsResults);
            }
            _browser.Navigate("");
            _browser.Dispose();

            Settings.Default.WindowWidth = Width;
            Settings.Default.WindowHeight = Height;
            Settings.Default.WindowIsMaximized = WindowState == WindowState.Maximized;
            Settings.Default.ArduinoPath = ArduinoPath;
            Settings.Default.SelectedPogrammer = SelectedProgrammer != null ? SelectedProgrammer.Name : "";
            Settings.Default.SelectedPort = SelectedPort;

            Settings.Default.SavedProgram = jsResults;

            Settings.Default.Save();

            foreach (var tempPath in _tempPathsCreated)
            {
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
                else if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);

                }
            }
        }
Exemplo n.º 12
0
		public override string ToString()
		{
			using (var context = new AutoJSContext())
			{
				return context.ConvertValueToString(this);
			}
		}
        void Upload_Click(object sender, RoutedEventArgs e)
        {
            string message;
            if (ValidateArduinoSetup(ArduinoPath, Programmers, SelectedProgrammer, ProgrammerPorts, SelectedPort, true, out message))
            {
                string jsResults;

                using (AutoJSContext context = new AutoJSContext(_browser.Window.JSContext))
                using (JSAutoCompartment compartment = new JSAutoCompartment(context, (nsISupports)_browser.Window.DomWindow))
                {
                    context.EvaluateScript("(Blockly.Generator.workspaceToCode('Arduino'))", out jsResults);
                }

                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(_browser.ClientRectangle.Width, _browser.ClientRectangle.Height);
                _browser.DrawToBitmap(bmp, _browser.ClientRectangle);

                var screenshot = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp.GetHbitmap(),
                    IntPtr.Zero,
                    System.Windows.Int32Rect.Empty,
                    BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height));

                //The following is like 3 card Monty with threads and contexts, but it does work ;)
                var loadingWindow = new UploadingWindow() { Owner = this, WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner};

                loadingWindow.BlocksImage.Source = screenshot;
                IsEnabled = false;

                loadingWindow.Loaded += (s, ev) => {
                    Task.Run(() =>
                    {
                        string errorText;
                        bool result = SendToArduino(true, jsResults, out errorText);
                        Dispatcher.InvokeAsync(() =>
                        {
                            loadingWindow.Close();
                            IsEnabled = true;
                            if (result)
                            {
                                MessageBox.Show(this, "Success!" ,"Upload Complete!",MessageBoxButton.OK,MessageBoxImage.Information);

                            }
                            else
                            {
                                MessageBox.Show(this, "There were problems:\n" + errorText ?? "UNKNOWN ERROR","Upload Failed :(", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                            }
                        } );

                    });

                };
                loadingWindow.ShowDialog();
            }
        }
		public void JS_TypeOfValue_OnBoolJsValCreatedBySpiderMonkey_ReturnsTypeBool()
		{
			var jsVal = CreateBoolJsVal(true);
			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{
				Assert.AreEqual(JSType.JSTYPE_BOOLEAN, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, jsVal));
			}
		}
		public void JS_TypeOfValue_OnStringJsValCreatedBySpiderMonkey_ReturnsTypeString()
		{

			var jsVal = CreateStringJsVal("hello world");
			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{
				Assert.AreEqual(JSType.JSTYPE_STRING, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, jsVal));
			}
		}
        public void EvaluateScript_Run500TimesNavigatingToANewDocumentEachTime_DoesNotCrash()
        {
            for (int i = 0; i < 500; i++)
            {
                GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, String.Format("{0}", i));//"hello <span>world</span>");
                //browser.TestLoadHtml(String.Format("{0}", i));

                using (AutoJSContext context = new AutoJSContext(browser.JSContext))
                {
                    string result;
                    context.EvaluateScript("2+3;", out result);
                    Assert.AreEqual("5", result);
                }
            }
        }
        public void EvaluateScript_PassBodysFirstChildAndPassToAInlineFunction_FunctionReturnsExpectedResults()
        {
            GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, "hello <span>world</span>");
            //browser.TestLoadHtml("hello <span>world</span>");

            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                context.EvaluateScript("function dosomthing(node) { return node.textContent; } dosomthing(this);", (nsISupports)browser.Document.Body.FirstChild.DomObject, out result);

                Assert.AreEqual("hello ", result);
            }
        }
        public void EvaluateScript_PassBodyasThis_ThisEqualsBodyObject()
        {
            GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, "hello world");
            //browser.TestLoadHtml("hello world");

            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                context.EvaluateScript("this;", (nsISupports)browser.Document.Body.DomObject, out result);

                Assert.AreEqual("[object HTMLBodyElement]", result);
            }
        }
        public void EvaluateScript_JavascriptAccessExistingGlobalObjects_ScriptExecutesAndReturnsExpectedResult()
        {
            GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, "hello world");
            //browser.TestLoadHtml("hello world");

            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                Assert.IsTrue(context.EvaluateScript("this", out result));
                Assert.AreEqual("[object Window]", result);

                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML;", out result));
                Assert.AreEqual("hello world", result);

                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML = 'hi';", out result));
                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML;", out result));
                Assert.AreEqual("hi", result);

                Assert.IsTrue(context.EvaluateScript("x=10;y=20;x*y;", out result));
                Assert.AreEqual("200", result);
            }
        }
        public void EvaluateScript_JavascriptAccessExistingGlobalObjectsWithoutNormalDocumentSetup_ScriptExecutesAndReturnsExpectedResult()
        {
            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                Assert.IsTrue(context.EvaluateScript("this", out result));
                Assert.AreEqual("[object Window]", result);

                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML;", out result));
                Assert.AreEqual(String.Empty, result);

                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML = 'hi';", out result));
                Assert.IsTrue(context.EvaluateScript("this.document.body.innerHTML;", out result));
                Assert.AreEqual("hi", result);

                Assert.IsTrue(context.EvaluateScript("x=10;y=20;x*y;", out result));
                Assert.AreEqual("200", result);
            }
        }
Exemplo n.º 21
0
        public static IntPtr GetJSContextForDomWindow(nsIDOMWindow window)
        {
            Xpcom.AssertCorrectThread();

            IntPtr pUnk = Marshal.GetIUnknownForObject(window);
            Marshal.Release(pUnk);

            IntPtr context;
            if (!_windowContexts.TryGetValue(pUnk, out context))
            {
                context = IntPtr.Zero;

                foreach (IntPtr cx in _unknownContexts)
                {
                    IntPtr pGlobal = SpiderMonkey.JS_GetGlobalObject(cx);
                    if (pGlobal != IntPtr.Zero)
                    {
                        using (var auto = new AutoJSContext(cx))
                        {
                            nsISupports global = auto.GetGlobalNsObject();
                            if (global != null)
                            {
                                var domWindow = Xpcom.QueryInterface<nsIDOMWindow>(global);
                                if (domWindow != null)
                                {
                                    try
                                    {
                                        IntPtr pUnkTest = Marshal.GetIUnknownForObject(domWindow.GetWindowAttribute());
                                        Marshal.Release(pUnkTest);

                                        if (pUnk == pUnkTest)
                                        {
                                            _windowContexts.Add(pUnk, cx);
                                            _unknownContexts.Remove(cx);
                                            context = cx;
                                            break;
                                        }
                                    }
                                    finally
                                    {
                                        Marshal.ReleaseComObject(domWindow);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return context;
        }
		public void JS_TypeOfValue_OnNumberJsValCreatedBySpiderMonkey_ReturnsTypeNumber()
		{

			var jsVal = CreateNumberJsVal(100);
			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{
				Assert.AreEqual(JSType.JSTYPE_NUMBER, SpiderMonkey.JS_TypeOfValue(cx.ContextPointer, jsVal));
			}
		}
Exemplo n.º 23
0
		public string RunJavaScript(string script)
		{
			var browser = ((GeckoWebBrowser)_pdfViewerControl);
			Debug.Assert(!InvokeRequired);
			Debug.Assert(browser.Window != null);
			if (browser.Window != null)
			{
				using (var context = new AutoJSContext(browser.Window))
				{
					string result;
					context.EvaluateScript(script, (nsISupports)browser.Document.DomObject, out result);
					return result;
				}
			}
			return null;
		}
		public void JS_NewStringCopyN()
		{
			using (AutoJSContext cx = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext))
			{
				IntPtr jsString = SpiderMonkey.JS_NewStringCopyN(cx.ContextPointer, "hello world", 11);
				Assert.NotNull(jsString);

				IntPtr str = SpiderMonkey.JS_EncodeString(cx.ContextPointer, jsString);
				string result = Marshal.PtrToStringAnsi(str);
				Assert.AreEqual("hello world", result);
			}
		}
Exemplo n.º 25
0
		public void BrowserPrint()
		{
			var browser = ((GeckoWebBrowser)_pdfViewerControl);
			using (AutoJSContext context = new AutoJSContext (browser.Window)) {
				nsIDOMWindow domWindow = browser.Window.DomWindow;
				nsIWebBrowserPrint print = Xpcom.QueryInterface<nsIWebBrowserPrint> (domWindow);

				try {
					if (PrintProgress != null)
					{
						// Send event to disable print, simple, outside cover and inside buttons
						// while printing
						PrintProgress.Invoke (this, new PdfPrintProgressEventArgs(true));
					}
					_printing = true;
					print.Print (null, this);
				} catch (COMException e) {
					if (PrintProgress != null) {
						PrintProgress.Invoke (this, new PdfPrintProgressEventArgs(false));
					}
					//NS_ERROR_ABORT means user cancelled the printing, not really an error.
					if (e.ErrorCode != GeckoError.NS_ERROR_ABORT)
						throw;
				}
				finally {
					Marshal.ReleaseComObject (print);
				}
			}
		}
 public void EvaluateScript_Run500Times_CreatingNewSafeAutoJSContextEachTime_DoesNotCrash()
 {
     for (int i = 0; i < 500; i++)
     {
         using (var safeContext = new AutoJSContext(IntPtr.Zero))
         {
             string result;
             safeContext.EvaluateScript("2+3;", out result);
             Assert.AreEqual("5", result);
         }
     }
 }
Exemplo n.º 27
0
		internal object ToComObject(IntPtr cx)
		{
			using (var context = new AutoJSContext(cx))
			{
				var jsObject = SpiderMonkey.JS_ValueToObject(context.ContextPointer, this);

				var guid = typeof(nsISupports).GUID;
				var pUnk = IntPtr.Zero;
				try
				{
					pUnk = Xpcom.XPConnect.Instance.WrapJS(context.ContextPointer, jsObject, ref guid);
					var comObj = Xpcom.GetObjectForIUnknown(pUnk);

					return comObj;
				}
				finally
				{
					if (pUnk != IntPtr.Zero)
					{
						Marshal.Release(pUnk);
					}
				}
			}
		}
        public void EvaluateScript_Run500Times_DoesNotCrash()
        {
            GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, string.Empty);
            //browser.TestLoadHtml("");

            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                for (int i = 0; i < 500; i++)
                {
                    string result;
                    context.EvaluateScript("2+3;", out result);
                    Assert.AreEqual("5", result);
                }
            }
        }
        public void EvaluateScript_SimpleJavascriptWithoutNormalDocumentSetup_ScriptExecutesAndReturnsExpectedResult()
        {
            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                Assert.IsTrue(context.EvaluateScript("3 + 2;", out result));
                Assert.AreEqual(5, Int32.Parse(result));

                Assert.IsTrue(context.EvaluateScript("'hello' + ' ' + 'world';", out result));
                Assert.AreEqual("hello world", result);
            }
        }
Exemplo n.º 30
0
		public void Print()
		{
#if !__MonoCS__
			var arc = _pdfViewerControl as AdobeReaderControl;
			if (arc != null)
			{
				// The print button is only enabled after we have generated a PDF and tried to display it,
				// so if we still have an ARC by this point, it displayed successfully, and presumably can also print.
				arc.Print();
				return;
			}

			// PDFjs printing has proved unreliable, so GhostScript is preferable even on Windows.
			if (TryGhostcriptPrint())
				return;

			var browser = ((GeckoWebBrowser)_pdfViewerControl);
			using (AutoJSContext context = new AutoJSContext(browser.Window))
			{
				string result;
				context.EvaluateScript(@"window.print()", (nsISupports)browser.Document.DomObject, out result);
			}
#else
			// on Linux the isntaller will have a dependency on GhostScript so it should always be available.
			// We've had many problems with PDFJs so hopefully this solves them.
			if (TryGhostcriptPrint())
				return;

			// BL-788 Print dialog appears behind Bloom on Linux
			// Finally went to minimizing Bloom to allow the print window to be
			// displayed and then restore to the original size after the
			// Print or Cancel button is pushed on the print dialog.
			_pauseTimer = new Timer();
			_pauseTimer.Interval = 250;
			_pauseTimer.Tick += PrintAfterPause;
			_savedState = this.ParentForm.WindowState;
			this.ParentForm.WindowState = FormWindowState.Minimized;
			_pauseTimer.Start();

#endif
		}
        public void EvaluateScript_SimpleJavascript_ScriptExecutesAndReturnsExpectedResult()
        {
            GeckoWebBrowserTextExtensionMethods.TestLoadHtml(browser, string.Empty);
            //browser.TestLoadHtml("");

            using (AutoJSContext context = new AutoJSContext(browser.JSContext))
            {
                string result;
                Assert.IsTrue(context.EvaluateScript("3 + 2;", out result));
                Assert.AreEqual(5, Int32.Parse(result));

                Assert.IsTrue(context.EvaluateScript("'hello' + ' ' + 'world';", out result));
                Assert.AreEqual("hello world", result);
            }
        }
Exemplo n.º 32
0
        private void FillFormField(string id, string value)
        {
            if (string.IsNullOrEmpty(id) && string.IsNullOrEmpty(value))
                return;

            // Only fill out the form field if we have an id
            if (!string.IsNullOrEmpty(id) || value == ConnectionManager.ParsingConstants.Click)
            {
                #region IE
                if (this.browserType == BrowserType.InternetExplorer)
                {
                    if (this.internetExplorer.Document == null)
                        return;

                    HtmlElement element = this.internetExplorer.Document.GetElementById(id);

                    // The element hasn't been found -> try to find it by name
                    if (element == null)
                    {
                        HtmlElementCollection collection = this.internetExplorer.Document.All;

                        foreach (HtmlElement e in collection)
                        {
                            if (e.Name == id)
                            {
                                element = e;
                                break;
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(id) && element != null)
                    {
                        if (value != ConnectionManager.ParsingConstants.Click & value != ConnectionManager.ParsingConstants.Redirect && value != ConnectionManager.ParsingConstants.Script)
                        {
                            element.SetAttribute("value", this.ParseValue(value));
                        }
                        else if (value == ConnectionManager.ParsingConstants.Click)
                        {
                            // Prevent the browser from looping
                            // e.g. a GMail user has entered a wrong pwd
                            // the browser would now loop until the site
                            // (which will never change) chages.
                            if (this.repeatedClickCount >= 1)
                            {
                                return;
                            }

                            this.repeatedClickCount++;

                            element.InvokeMember("click");
                        }
                    }
                    else if (value == ConnectionManager.ParsingConstants.Click)
                    {
                        HtmlElementCollection collection = this.internetExplorer.Document.All;

                        if (collection == null)
                        {
                            return;
                        }

                        for (int i = 0; i < collection.Count; i++)
                        {
                            element = collection[i];

                            string type = element.GetAttribute("type");

                            if (!string.IsNullOrEmpty(type))
                            {
                                if (element.GetAttribute("type").ToLowerInvariant() == "submit")
                                {
                                    // Prevent the browser from looping
                                    // e.g. a GMail user has entered a wrong pwd
                                    // the browser would now loop until the site
                                    // (which will never change) chages.
                                    if (this.repeatedClickCount >= 1)
                                    {
                                        return;
                                    }

                                    this.repeatedClickCount++;

                                    element.InvokeMember("click");
                                }
                            }
                        }
                    }
                    else if (value == ConnectionManager.ParsingConstants.Redirect & redirected == false) 
                    {
                        redirected = true;
                        this.Home = id;
                        this.internetExplorer.Navigate(id);
                    }
                    else if (value == ConnectionManager.ParsingConstants.Script)
                    {
                        string script = id;
                        string functionName = GetScriptFunctionName(ref script);

                        HtmlElement head = internetExplorer.Document.GetElementsByTagName("head")[0];
                        HtmlElement scriptElement = internetExplorer.Document.CreateElement("script");
                        scriptElement.SetAttribute("text", script);
                        head.AppendChild(scriptElement);
                       
                        this.internetExplorer.Document.InvokeScript(functionName);
                    }
                }
                #endregion
                #region FF
                #if GECKO
                else if (this.browserType == BrowserType.Firefox)
                {
                    if (this.firefox.Document != null)
                    {
                        GeckoElement element = this.firefox.Document.GetElementById(id);

                        bool useName = false;

                        // The element hasn't been found -> try to find it by name
                        if (element == null)
                        {
                            GeckoElementCollection collection = this.firefox.Document.GetElementsByName(id);

                            if (collection != null && collection.Length >= 1)
                                element = collection[0];

                            useName = true;

                            if (element == null && value != ConnectionManager.ParsingConstants.Redirect && value != ConnectionManager.ParsingConstants.Click && value != ConnectionManager.ParsingConstants.Script)
                            {
                                return;
                            }
                        }

                        if (value != ConnectionManager.ParsingConstants.Click && value != ConnectionManager.ParsingConstants.Redirect && value != ConnectionManager.ParsingConstants.Script)
                        {
                            // The below code doesn't work
                            // element.SetAttribute("value", this.ParseValue(value));

                            using (AutoJSContext context = new AutoJSContext(firefox.Window.JSContext))
                            {
                                string result;
                                
                                // by id
                                if(!useName)
                                    context.EvaluateScript(string.Format("document.getElementById('{0}').value = '{1}';", id, this.ParseValue(value)), out result);
                                // by name
                                else
                                    context.EvaluateScript(string.Format("document.GetElementsByName('{0}')[0].value = '{1}';", id, this.ParseValue(value)), out result);

                                if (result.Equals("undefined"))
                                {
                                    return;
                                }
                            }

                        }
                        else if (value == ConnectionManager.ParsingConstants.Click)
                        {
                            // Prevent the browser from looping
                            // e.g. a GMail user has entered a wrong pwd
                            // the browser would now loop until the site
                            // (which will never change) chages.
                            if (this.repeatedClickCount >= 1)
                            {
                                return;
                            }

                            this.repeatedClickCount++;

                            if (element == null)
                            {
                                IEnumerable<GeckoHtmlElement> collection = this.firefox.Document.GetElementsByTagName("input");

                                if (collection == null)
                                {
                                    return;
                                }

                                foreach (GeckoHtmlElement el in collection)
                                {
                                    string type = el.GetAttribute("type");

                                    if (!string.IsNullOrEmpty(type))
                                    {
                                        if (el.GetAttribute("type").ToLowerInvariant() == "submit")
                                        {
                                            // Prevent the browser from looping
                                            // e.g. a GMail user has entered a wrong pwd
                                            // the browser would now loop until the site
                                            // (which will never change) chages.
                                            if (this.repeatedClickCount >= 1)
                                            {
                                                return;
                                            }

                                            this.repeatedClickCount++;

                                            (el).Click();
                                        }
                                    }
                                }
                            }
                            else
                                ((GeckoInputElement)element).Click();
                        }
                        else if (value == ConnectionManager.ParsingConstants.Redirect & redirected == false)
                        {
                            redirected = true;
                            this.Home = id;
                            this.firefox.Navigate(id);
                        }
                        else if (value == ConnectionManager.ParsingConstants.Script)
                        {
                            string script = id;
                            //string functionName = GetScriptFunctionName(ref script);

                            if (prevScript == script)
                            {
                                prevScript = null;
                                return;
                            }

                            if (string.IsNullOrEmpty(prevScript) || prevScript != script)
                                prevScript = script;

                            using (AutoJSContext context = new AutoJSContext(firefox.Window.JSContext))
                            {                               
                                string result;
                                context.EvaluateScript(script, out result);
                            }
                        }
                    }
                }
                #endif
                #endregion
            }
        }
Exemplo n.º 33
0
 private void RunJavascript(string javascript)
 {
     using (var context = new AutoJSContext(geckoWebBrowser1.Window.JSContext))
     {
         context.EvaluateScript(javascript);
     }
 }
Exemplo n.º 34
0
 public string RunJavaScript(string script)
 {
     Debug.Assert(!InvokeRequired);
     // Review JohnT: does this require integration with the NavigationIsolator?
     if (_browser.Window != null) // BL-2313 two Alt-F4s in a row while changing a folder name can do this
     {
         using (var context = new AutoJSContext(_browser.Window))
         {
             string result;
             context.EvaluateScript(script, (nsISupports)_browser.Document.DomObject, out result);
             return result;
         }
     }
     return null;
 }
Exemplo n.º 35
0
        internal static IntPtr GetJSContextForDomWindow(nsIDOMWindow window)
        {
            IntPtr            context     = IntPtr.Zero;
            nsIDOMEventTarget eventTarget = window.GetWindowRootAttribute();

            try
            {
                context = eventTarget.GetJSContextForEventHandlers();
                if (context == IntPtr.Zero)
                {
                    IntPtr pUnk = Marshal.GetIUnknownForObject(window);
                    Marshal.Release(pUnk);


                    if (!_windowContexts.TryGetValue(pUnk, out context))
                    {
                        context = IntPtr.Zero;

                        IntPtr cx;
                        IntPtr iterp = IntPtr.Zero;
                        IntPtr rt    = Runtime;
                        while ((cx = SpiderMonkey.JS_ContextIterator(rt, ref iterp)) != IntPtr.Zero)
                        {
                            IntPtr pGlobal = SpiderMonkey.DefaultObjectForContextOrNull(cx);
                            if (pGlobal != IntPtr.Zero)
                            {
                                using (var auto = new AutoJSContext(cx))
                                {
                                    using (ComPtr <nsISupports> global = auto.GetGlobalNsObject())
                                    {
                                        if (global != null)
                                        {
                                            var domWindow = Xpcom.QueryInterface <nsIDOMWindow>(global.Instance);
                                            if (domWindow != null)
                                            {
                                                try
                                                {
                                                    IntPtr pUnkTest = Marshal.GetIUnknownForObject(domWindow.GetWindowAttribute());
                                                    Marshal.Release(pUnkTest);

                                                    if (pUnk == pUnkTest)
                                                    {
                                                        _windowContexts.Add(pUnk, cx);
                                                        context = cx;
                                                        break;
                                                    }
                                                }
                                                finally
                                                {
                                                    Xpcom.FreeComObject(ref domWindow);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (eventTarget != null)
                {
                    Xpcom.FreeComObject(ref eventTarget);
                }
            }
            return(context);
        }