public IEnumerable<GeckoElement> GetElementsByJQuery(string jQuery) { JsVal jsValue; var elements = new List<GeckoElement>(); using (var autoContext = new AutoJSContext()) { autoContext.PushCompartmentScope((nsISupports)m_Window.Document.DomObject); jsValue = autoContext.EvaluateScript(jQuery); if (!jsValue.IsObject) return elements; if (!SpiderMonkey.JS_HasProperty(autoContext.ContextPointer, jsValue.AsPtr, "length")) { return null; } var length = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, "length").ToInteger(); if (length == 0) { return null; } for (var elementIndex = 0; elementIndex < length; elementIndex++) { var firstNativeDom = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, elementIndex.ToString(CultureInfo.InvariantCulture)).ToComObject(autoContext.ContextPointer); var element = Xpcom.QueryInterface<nsIDOMHTMLElement>(firstNativeDom); if (element != null) { elements.Add(GeckoHtmlElement.Create(element)); } } } return elements; }
private static string CopyImageElementToDataImageString(GeckoHtmlElement element, string imageFormat, float xOffset, float yOffset, float width, float height) { if (width == 0) throw new ArgumentException("width"); if (height == 0) throw new ArgumentException("height"); string data; using (var context = new AutoJSContext()) { context.EvaluateScript(string.Format(@"(function(element, canvas, ctx) {{ canvas = element.ownerDocument.createElement('canvas'); canvas.width = {2}; canvas.height = {3}; ctx = canvas.getContext('2d'); ctx.drawImage(element, -{0}, -{1}); return canvas.toDataURL('{4}'); }} )(this)", xOffset, yOffset, width, height, imageFormat), (nsISupports)(nsIDOMElement)element.DomObject, out data); } return data; }
internal static GeckoCanvasElement CreateCanvasOfImageElement(IGeckoWebBrowser browser, GeckoHtmlElement element, float xOffset, float yOffset, float width, float height) { if (width == 0) throw new ArgumentException("width"); if (height == 0) throw new ArgumentException("height"); // Some opertations fail without a proper JSContext. using(var jsContext = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext)) { GeckoCanvasElement canvas = (GeckoCanvasElement)browser.Document.CreateElement("canvas"); canvas.Width = (uint)width; canvas.Height = (uint)height; nsIDOMHTMLCanvasElement canvasPtr = (nsIDOMHTMLCanvasElement)canvas.DomObject; nsIDOMCanvasRenderingContext2D context; using (var str = new nsAString("2d")) { context = (nsIDOMCanvasRenderingContext2D)canvasPtr.MozGetIPCContext(str); } context.DrawImage((nsIDOMElement)element.DomObject, xOffset, yOffset, width, height, xOffset, yOffset, width, height, 6); return canvas; } }
public string ToDataURL(string type) { using (var context = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext)) using (nsAString retval = new nsAString(), param = new nsAString(type)) { JsVal js = default(JsVal); DOMHTMLElement.ToDataURL(param, ref js, context.ContextPointer, retval); return retval.ToString(); } }
public JsVal ExecuteJQuery(string jQuery) { JsVal jsValue; using (var autoContext = new AutoJSContext()) { autoContext.PushCompartmentScope((nsISupports)m_Window.DomWindow); jsValue = autoContext.EvaluateScript(jQuery); } return jsValue; }
public GeckoElement GetElementByJQuery(string jQuery) { JsVal jsValue; using (var autoContext = new AutoJSContext()) { autoContext.PushCompartmentScope((nsISupports)m_Window.Document.DomObject); jsValue = autoContext.EvaluateScript(jQuery); if (jsValue.IsObject) { var nativeComObject = jsValue.ToComObject(autoContext.ContextPointer); var element = Xpcom.QueryInterface<nsIDOMHTMLElement>(nativeComObject); if (element != null) { return GeckoHtmlElement.Create(element); } if (!SpiderMonkey.JS_HasProperty(autoContext.ContextPointer, jsValue.AsPtr, "length")) { return null; } var length = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, "length").ToInteger(); if (length == 0) { return null; } var firstNativeDom = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, "0").ToComObject(autoContext.ContextPointer); element = Xpcom.QueryInterface<nsIDOMHTMLElement>(firstNativeDom); if (element != null) { return GeckoHtmlElement.Create(element); } } } return null; }
public IEnumerable <GeckoElement> GetElementsByJQuery(string jQuery) { JsVal jsValue; var elements = new List <GeckoElement>(); using (var autoContext = new AutoJSContext()) { autoContext.PushCompartmentScope((nsISupports)_window.Document.DomObject); jsValue = autoContext.EvaluateScript(jQuery, _window.DomWindow); if (!jsValue.IsObject) { return(elements); } if (!SpiderMonkey.JS_HasProperty(autoContext.ContextPointer, jsValue.AsPtr, "length")) { return(null); } var length = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, "length").ToInteger(); if (length == 0) { return(null); } for (var elementIndex = 0; elementIndex < length; elementIndex++) { var firstNativeDom = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, elementIndex.ToString(CultureInfo.InvariantCulture)).ToComObject(autoContext.ContextPointer); var element = Xpcom.QueryInterface <nsIDOMHTMLElement>(firstNativeDom); if (element != null) { elements.Add(GeckoHtmlElement.Create(element)); } } } return(elements); }
public IEnumerable <GeckoElement> GetElementsByJQuery(string jQuery) { using (var autoContext = new AutoJSContext(_window)) { var jsValue = autoContext.EvaluateScript(jQuery, _window.DomWindow); if (!jsValue.IsObject) { return(new List <GeckoElement>()); } if (!SpiderMonkey.JS_HasProperty(autoContext.ContextPointer, jsValue.AsPtr, "length")) { return(new List <GeckoElement>()); } var length = SpiderMonkey.JS_GetProperty(autoContext.ContextPointer, jsValue.AsPtr, "length").ToInteger(); if (length == 0) { return(new List <GeckoElement>()); } return(Enumerable.Range(0, length).Select(elementIndex => CreateHtmlElementFromDom(autoContext, jsValue, elementIndex)).Where(element => element != null).ToList()); } }
public void SetProperty(string propertyName, object value) { using (var context = new AutoJSContext(_globalWindowProxy)) using (var jsObject = context.ConvertCOMObjectToJSObject(_thisObject, true)) { DisposablCollection disposablCollection; var types = ConvertTypes(new[] { value }, context, out disposablCollection).First(); var jso = jsObject.JSObject; try { if (!SpiderMonkey.JS_SetProperty(context.ContextPointer, ref jso, propertyName, ref types)) { throw new GeckoException( String.Format("Property '{0}' of value '{1}' could not be set on object", propertyName, value)); } } finally { disposablCollection.Dispose(); } } }
void save(string json) { this.Title = "正在保存..."; Helper.Remote.Invoke <SunRizServer.ControlWindow>("SaveWindowContent", (ret, err) => { if (err != null) { MessageBox.Show(this.GetParentByName <Window>(null), err); } else { using (var jsContext = new AutoJSContext(_gecko.Window)) { jsContext.EvaluateScript("editor.changed=false"); } if (_dataModel.id == null) { _dataModel.CopyValue(ret); _parentNode.Nodes.Add(new ControlWindowNode(_dataModel)); } else { _dataModel.CopyValue(ret); } _dataModel.ChangedProperties.Clear(); this.Title = _dataModel.Name; if (closeAfterSave) { closeAfterSave = false; MainWindow.Instance.CloseDocument(this); } } this.Title = _dataModel.Name; }, _dataModel, json); }
void loadFinish(string msg) { _gecko.DomClick -= _gecko_DomClick; _gecko.DomClick += _gecko_DomClick; this.Title = _dataModel.Name; try { if (IsRunMode) { //运行状态,设置窗口的标题文字 this.GetParentByName <Window>(null).Title = _dataModel.Name; } } catch { } _gecko.Enabled = true; if (_SelectWebControlByPointNameTask != null) { this.SelectWebControlByPointName(_SelectWebControlByPointNameTask); _SelectWebControlByPointNameTask = null; } if (IsRunMode) { try { using (var jsContext = new AutoJSContext(_gecko.Window)) { jsContext.EvaluateScript("run()"); } } catch (Exception ex) { MessageBox.Show(this.GetParentByName <Window>(null), ex.Message); } } }
void Load_Click(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog() { Filter = "Robot Block Files | *.blocks" }; if (dlg.ShowDialog(this) ?? false) { string tempPath = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName()); Directory.CreateDirectory(tempPath); string tempLoadingFile = IOPath.Combine(tempPath, "temp_blocks.xml"); File.Copy(dlg.FileName, tempLoadingFile, true); _tempPathsCreated.Add(tempPath); string fileUri = "file://" + new FileInfo(tempLoadingFile).FullName; using (var context = new AutoJSContext(_browser.Window.JSContext)) using (var compartment = new JSAutoCompartment(context, (nsISupports)_browser.Window.DomWindow)) { string output; context.EvaluateScript("load_by_url('" + fileUri.Replace("\\", "/") + "');", out output); } } }
public void FromPtr_JsObject_ConvertedToJsValOfExpectedObject() { var browser = new GeckoWebBrowser(); var unused = browser.Handle; Assert.IsNotNull(browser); browser.TestLoadHtml("hello world."); Assert.Null(browser.Editor); using (var context = new AutoJSContext(browser.Window)) { var jsObject = context.ConvertCOMObjectToJSObject((nsISupports)browser.Document.DomObject); var jsVal = JsVal.FromPtr(jsObject); Assert.IsTrue(jsVal.IsObject); Assert.AreEqual(JSType.JSTYPE_OBJECT, jsVal.Type); Assert.AreEqual("[object HTMLDocument]", jsVal.ToString()); // Verify that converting back to ComObject yields expected object. var documentObject = (nsIDOMHTMLDocument)jsVal.ToObject(); Assert.AreEqual(browser.Document.TextContent, new GeckoDocument(documentObject).TextContent); } browser.Dispose(); }
internal static JsVal CreateStringJsVal(AutoJSContext context, string value) { string jscript = String.Format("'{0}';", value); return(CreateJsVal(context, jscript)); }
/// <summary> /// 运行js代码 /// </summary> /// <typeparam name="T">返回值类型</typeparam> /// <param name="jsCode">一段js代码。如:return data.name;</param> /// <param name="data">传到js里面的对象,js可以通过data.*直接使用此参数</param> /// <returns></returns> public T Run <T>(string jsCode, object data) { if (httpServer == null) { throw new Exception("请先调用JsRunner.StartVirtualWebServer启动web服务器"); } var gecko = new GeckoWebBrowser(); gecko.CreateControl(); //加入apicloud.db模拟器 List <ISimulator> simulators = new List <ISimulator>(); foreach (var t in SimulatorTypes) { var obj = (ISimulator)Activator.CreateInstance(t); obj.Init(gecko); simulators.Add(obj); } bool loadFinished = false; gecko.NavigationError += (s, e) => { }; gecko.NSSError += (s, e) => { }; gecko.DocumentCompleted += (s, e) => { loadFinished = true; }; using (System.IO.MemoryStream ms = new MemoryStream()) { System.IO.StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); sw.WriteLine("<!DOCTYPE html>"); sw.WriteLine("<html>"); sw.WriteLine("<body>"); foreach (var simulator in simulators) { simulator.OnWritingScript(sw); } foreach (var path in JsFiles) { if (path[1] == ':') { if (File.Exists(path) == false) { throw new Exception($"文件{path}不存在"); } sw.WriteLine("<script src=\"file:///" + path + "\" type=\"text/javascript\"></script>"); } else { sw.WriteLine("<script src=\"" + path + "\" type=\"text/javascript\"></script>"); } } if (!string.IsNullOrEmpty(this.Html)) { sw.WriteLine(this.Html); } string result; if (_runJsOnWindowLoad) { sw.WriteLine("</body>"); sw.WriteLine("</html>"); sw.Dispose(); var pageid = Guid.NewGuid().ToString("N"); VisitHandler.HtmlContents.TryAdd(pageid, ms.ToArray()); ms.Dispose(); gecko.Navigate($"{ServerUrl}Jack.JSUnitTest?id={pageid}"); while (!loadFinished) { System.Threading.Thread.Sleep(10); System.Windows.Forms.Application.DoEvents(); } var jsContext = new AutoJSContext(gecko.Window); var js = @" (function(d){ var result = (function(data){ try{ " + jsCode + @" } catch(e) { if(typeof e === 'string') return { ______err : e , line:0 }; else { var msg = e.message; if(e.name) msg = e.name + ',' + msg; return { ______err :msg , line:e.lineNumber }; } } })(d); return JSON.stringify(result); })(" + (data == null ? "null" : Newtonsoft.Json.JsonConvert.SerializeObject(data)) + @"); "; jsContext.EvaluateScript(js, out result); jsContext.Dispose(); } else { var guidName = "v" + Guid.NewGuid().ToString("N"); var js = @" <script lang='ja'> var " + guidName + @" = (function(data){ try{ " + jsCode + @" } catch(e) { if(typeof e === 'string') return { ______err : e , line:0 }; else { var msg = e.message; if(e.name) msg = e.name + ',' + msg; return { ______err :msg , line:e.lineNumber }; } } })(" + Newtonsoft.Json.JsonConvert.SerializeObject(data) + @"); " + guidName + @"=JSON.stringify(" + guidName + @"); </script> "; sw.WriteLine(js); sw.WriteLine("</body>"); sw.WriteLine("</html>"); sw.Dispose(); var pageid = Guid.NewGuid().ToString("N"); VisitHandler.HtmlContents.TryAdd(pageid, ms.ToArray()); ms.Dispose(); gecko.Navigate($"{ServerUrl}Jack.JSUnitTest?id={pageid}"); while (!loadFinished) { System.Threading.Thread.Sleep(10); System.Windows.Forms.Application.DoEvents(); } var jsContext = new AutoJSContext(gecko.Window); js = guidName; jsContext.EvaluateScript(js, out result); jsContext.Dispose(); } gecko.Dispose(); if (result.StartsWith("{\"______err\":")) { var errObj = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(result); string errMsg = errObj.Value <string>("______err"); //int lineNumber = errObj.Value<int>("line") - 3; throw new Exception(errMsg); } if (result.StartsWith("\"") == false && typeof(T) == typeof(string)) { return((T)(object)result); } if (result == "undefined") { return(default(T)); } return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(result)); } }
public void BeforeEachTestSetup() { _gwb = new GeckoWebBrowser(); _gwb.CreateControl(); _context = new AutoJSContext(_gwb.Window); }
private static List <JsVal> ConvertTypes(object[] paramObjects, AutoJSContext context, out DisposablCollection toDispose) { List <IDisposable> list = new List <IDisposable>(); toDispose = new DisposablCollection(list); var collection = new List <JsVal>(); if (paramObjects == null) { return(collection); } foreach (var p in paramObjects) { JsVal val; if (p is nsAString || p is nsACString || p is nsAUTF8String || p is String) { val = SpiderMonkey.StringToJsVal(context.ContextPointer, p.ToString()); } else if (p is nsISupports) { // This returns a [xpconnect wrapped nsISupports] - why may or may not be good enought - if not could try and access the objects wrappedJSObject property? // val = SpiderMonkey.JS_CallFunctionName(context.ContextPointer, jsObject, "valueOf"); // Replaced CallFunctionName 'valueOf' method with 'managed convert' (for speed reasons) var jso = context.ConvertCOMObjectToJSObject((nsISupports)p, false); list.Add(jso); val = JsVal.FromPtr(jso.JSObject); } else if (p is bool) { val = CreateBoolJsVal(context, (bool)p); } else if (p is double) { val = JsVal.FromDouble((double)p); } else if (p is int) { val = JsVal.FromDouble(Convert.ToDouble(p)); } else if (p is WebIDLUnionBase) { WebIDLUnionBase b = (WebIDLUnionBase)p; if (b.IsNull()) { SpiderMonkey.JS_ExecuteScript(context.ContextPointer, "null", out val); } else if (b.IsComObject()) { var item = ((WebIDLUnionBase)p).ToComObject(); var jso = context.ConvertCOMObjectToJSObject(item, false); list.Add(jso); val = JsVal.FromPtr(jso.JSObject); } else if (b.IsBool()) { val = CreateBoolJsVal(context, b.ToBool()); } else { throw new NotImplementedException("WebIDLUnion are currently only supported for nsISupport and bool types and null's."); } } else { SpiderMonkey.JS_ExecuteScript(context.ContextPointer, (p ?? "null").ToString(), out val); } collection.Add(val); } return(collection); }
public void GetVideoLink() { web.CreateWindow += CloseWindow; new Thread(() => { string Url = ""; web.Invoke((MethodInvoker) delegate() { using (AutoJSContext context = new AutoJSContext(web.Window)) { context.EvaluateScript("document.URL;", out Url); } }); while (Url == "") { ; } //if (!Url.Contains("bs.to")) //{ // web.Navigate(Link); // web.DocumentCompleted += CaptchaSiteBack; //} //else //{ // ready = true; //} ready = true; while (!ready) { ; } Point audioBTN = FindPicture("BypassGoogle\\audioBTN.png"); LeftMouseClick(audioBTN); Thread.Sleep(300); Point downloadBTN = FindPicture("BypassGoogle\\downloadBTN.png"); LeftMouseClick(downloadBTN); while (AudioLink == "") { ; } WebClient wbc = new WebClient(); wbc.DownloadFile(AudioLink, "BypassGoogle\\audio.mp3"); string TextMeaning = UnderstandAudio().Replace("\n", "").Replace("\r", ""); Thread.Sleep(rnd.Next(100, 200)); Point Textfield = downloadBTN; Textfield.Y -= rnd.Next(33, 43); Textfield.X += rnd.Next(0, 50); LeftMouseClick(Textfield); Thread.Sleep(rnd.Next(10, 50)); InputSimulator sim = new InputSimulator(); foreach (char item in TextMeaning) { VirtualKeyCode c = VirtualKeyCode.VK_0; switch (item.ToString().ToLower().ToCharArray()[0]) { case 'a': c = VirtualKeyCode.VK_A; break; case 'b': c = VirtualKeyCode.VK_B; break; case 'c': c = VirtualKeyCode.VK_C; break; case 'd': c = VirtualKeyCode.VK_D; break; case 'e': c = VirtualKeyCode.VK_E; break; case 'f': c = VirtualKeyCode.VK_F; break; case 'g': c = VirtualKeyCode.VK_G; break; case 'h': c = VirtualKeyCode.VK_H; break; case 'i': c = VirtualKeyCode.VK_I; break; case 'j': c = VirtualKeyCode.VK_J; break; case 'k': c = VirtualKeyCode.VK_K; break; case 'l': c = VirtualKeyCode.VK_L; break; case 'm': c = VirtualKeyCode.VK_M; break; case 'n': c = VirtualKeyCode.VK_N; break; case 'o': c = VirtualKeyCode.VK_O; break; case 'p': c = VirtualKeyCode.VK_P; break; case 'q': c = VirtualKeyCode.VK_Q; break; case 'r': c = VirtualKeyCode.VK_R; break; case 's': c = VirtualKeyCode.VK_S; break; case 't': c = VirtualKeyCode.VK_T; break; case 'u': c = VirtualKeyCode.VK_U; break; case 'v': c = VirtualKeyCode.VK_V; break; case 'w': c = VirtualKeyCode.VK_W; break; case 'x': c = VirtualKeyCode.VK_X; break; case 'y': c = VirtualKeyCode.VK_Y; break; case 'z': c = VirtualKeyCode.VK_Z; break; case ' ': c = VirtualKeyCode.SPACE; break; } sim.Keyboard.KeyPress(c); Thread.Sleep(rnd.Next(50, 100)); } Point submit = FindPicture("BypassGoogle\\submit.png"); LeftMouseClick(submit); }).Start(); }
void writePointValue(string arg) { try { string[] pointValue = arg.ToJsonObject <string[]>(); string pointName = pointValue[0]; // /p/a/01 string addr = pointValue[1]; // 点真实路径 if (string.IsNullOrEmpty(addr)) { //查询点真实地址 try { if (_PointAddress.ContainsKey(pointName) == false) { _PointAddress[pointName] = Helper.Remote.InvokeSync <PointAddrInfo>("GetPointAddr", pointName); } addr = _PointAddress[pointName].addr; } catch { throw new Exception($"无法获取点“{pointName}”真实地址"); } } string value = pointValue[2]; var client = _clients.FirstOrDefault(m => m.WatchingPointNames.Contains(pointName)); if (client == null) { //构造MyDriverClient var device = Helper.Remote.InvokeSync <SunRizServer.Device>("GetDeviceAndDriver", _PointAddress[pointName].deviceId); client = new MyDriverClient(device.Driver.Address, device.Driver.Port.Value); client.Device = device; client.WatchingPoints.Add(addr); client.WatchingPointNames.Add(pointName); _clients.Add(client); } if (client != null) { var pointObj = _AllPoints.FirstOrDefault(m => m.Value <string>("addr") == addr); if (pointObj != null) { //转换数值 value = SunRizDriver.Helper.GetRealValue(pointObj, value).ToString(); } if (client.WriteValue(client.Device.Address, addr, value) == false) { System.Windows.Forms.MessageBox.Show(_gecko, "写入值失败!"); } else { using (var jsContext = new AutoJSContext(_gecko.Window)) { jsContext.EvaluateScript($"onReceiveValueFromServer({ (new { addr = addr, value = value }).ToJsonString()})"); } } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(_gecko, ex.Message); } }
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 == null || 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 } }
public FormGecko() { this.ShowInTaskbar = false; this.WindowState = FormWindowState.Minimized; string path = Path.Combine(Application.StartupPath, @"Service\FF33"); Xpcom.Initialize(path); login(); //disable(); //logout(); #region [ === CONFIG GECKO === ] //////// Uncomment the follow line to enable error page //////GeckoPreferences.User["browser.xul.error_pages.enabled"] = true; //////GeckoPreferences.User["gfx.font_rendering.graphite.enabled"] = true; //////GeckoPreferences.User["full-screen-api.enabled"] = true; //////GeckoPreferences.User["security.warn_viewing_mixed"] = false; //////GeckoPreferences.User["plugin.state.flash"] = 0; //////GeckoPreferences.User["browser.cache.disk.enable"] = false; //////GeckoPreferences.User["browser.cache.memory.enable"] = false; //////GeckoPreferences.User["permissions.default.image"] = 2; ////////string sUserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36"; ////////GeckoPreferences.User["general.useragent.override"] = sUserAgent; //GeckoPreferences.User["security.warn_viewing_mixed"] = false; GeckoPreferences.User["plugin.state.flash"] = 0; GeckoPreferences.User["browser.cache.disk.enable"] = false; GeckoPreferences.User["browser.cache.memory.enable"] = false; GeckoPreferences.User["permissions.default.image"] = 2; GeckoPreferences.User["browser.xul.error_pages.enabled"] = false; GeckoPreferences.User["security.enable_ssl2"] = true; GeckoPreferences.User["security.default_personal_cert"] = "Ask Never"; GeckoPreferences.User["security.warn_entering_weak"] = false; GeckoPreferences.User["security.warn_viewing_mixed"] = false; GeckoPreferences.User["dom.disable_open_during_load"] = true; GeckoPreferences.User["dom.allow_scripts_to_close_windows"] = false; GeckoPreferences.User["dom.popup_maximum"] = 0; ////GeckoPreferences.User["dom.max_script_run_time"] = 5; #endregion browser = new GeckoWebBrowser(); browser.Dock = DockStyle.Fill; this.Controls.Add(browser); browser.DocumentTitleChanged += (se2, ev2) => { string url = browser.Url.ToString(); if (url.StartsWith("http://*****:*****@" var arr = [], l = document.links; for(var i=0; i<l.length; i++) { var _href = l[i].href; if(_href.indexOf('https://accounts.google.com/Logout?') == 0){ arr.push(_href); } } ; var _link = arr.join('\n'); _link; "; using (AutoJSContext context = new AutoJSContext(browser.Window.JSContext)) { context.EvaluateScript(JS, (nsISupports)browser.Window.DomWindow, out val); if (!string.IsNullOrEmpty(val)) { m_Status = GStatus.LOGOUT_FINISH; browser.Navigate(val); } } return; } if (m_Status == GStatus.LOGOUT_FINISH) { clearCookie(); m_Status = GStatus.DISABLE; browser.Navigate("https://www.google.com.vn/"); return; } #endregion #region [ === LOGIN === ] var submit_approve_access = browser.Document.GetElementById("submit_approve_access"); if (submit_approve_access != null) { m_Status = GStatus.SUBMIT_APPROVE_ACCESS; } switch (m_Status) { case GStatus.NONE: case GStatus.LOGIN_EMAIL: var email = browser.Document.GetElementById("Email"); if (email != null) { m_Status = GStatus.LOGIN_EMAIL; JS = @"setTimeout(function(){ document.getElementById('Email').value = '*****@*****.**'; document.getElementById('next').click(); },3000); "; using (AutoJSContext context = new AutoJSContext(browser.Window.JSContext)) { context.EvaluateScript(JS, (nsISupports)browser.Window.DomWindow, out val); m_Status = GStatus.LOGIN_PASS; } } break; case GStatus.LOGIN_PASS: var pass = browser.Document.GetElementById("password"); if (pass != null) { m_Status = GStatus.LOGIN_PASS; JS = @"setTimeout(function(){ document.getElementById('password').value = 'thinhtu710'; document.getElementById('submit').click(); },3000); "; using (AutoJSContext context = new AutoJSContext(browser.Window.JSContext)) { context.EvaluateScript(JS, (nsISupports)browser.Window.DomWindow, out val); m_Status = GStatus.SUBMIT_APPROVE_ACCESS; } } break; case GStatus.SUBMIT_APPROVE_ACCESS: JS = @"setTimeout(function(){ document.getElementById('submit_approve_access').click(); },5000); "; using (AutoJSContext context = new AutoJSContext(browser.Window.JSContext)) { context.EvaluateScript(JS, (nsISupports)browser.Window.DomWindow, out val); m_Status = GStatus.FINISH; } break; case GStatus.FINISH: break; } #endregion }; this.Shown += (se, ev) => { this.Hide(); //this.WindowState = FormWindowState.Maximized; browser.Navigate(URL); }; }//end C'tor
public void CSharpInvokingJavascriptComObjects() { // Note: Firefox 17 removed enablePrivilege #546848 - refactored test so that javascript to create "@mozillazine.org/example/priority;1" is now executated by AutoJsContext // Register a C# COM Object // TODO would be nice to get nsIComponentRegistrar the xpcom way with CreateInstance // ie Xpcom.CreateInstance<nsIComponentRegistrar>(... Guid aClass = new Guid("a7139c0e-962c-44b6-bec3-aaaaaaaaaaac"); var factory = new MyCSharpClassThatContainsXpComJavascriptObjectsFactory(); Xpcom.ComponentRegistrar.RegisterFactory(ref aClass, "Example C sharp com component", "@geckofx/myclass;1", factory); // In order to use Components.classes etc we need to enable certan privileges. GeckoPreferences.User["capability.principal.codebase.p0.granted"] = "UniversalXPConnect"; GeckoPreferences.User["capability.principal.codebase.p0.id"] = "file://"; GeckoPreferences.User["capability.principal.codebase.p0.subjectName"] = ""; GeckoPreferences.User["security.fileuri.strict_origin_policy"] = false; #if PORT browser.JavascriptError += (x, w) => Console.WriteLine("Message = {0}", w.Message); #endif string intialPage = "<html><body></body></html>"; string initialjavascript = "var myClassInstance = Components.classes['@geckofx/myclass;1'].createInstance(Components.interfaces.nsIWebPageDescriptor);" + "var reg = myClassInstance.currentDescriptor.QueryInterface(Components.interfaces.nsIComponentRegistrar);" + "Components.utils.import(\"resource://gre/modules/XPCOMUtils.jsm\"); " + "const nsISupportsPriority = Components.interfaces.nsISupportsPriority;" + "const nsISupports = Components.interfaces.nsISupports;" + "const CLASS_ID = Components.ID(\"{1C0E8D86-B661-40d0-AE3D-CA012FADF170}\");" + "const CLASS_NAME = \"My Supports Priority Component\";" + "const CONTRACT_ID = \"@mozillazine.org/example/priority;1\";" + "function MyPriority() {" + " this._priority = nsISupportsPriority.PRIORITY_LOWEST;"+ "};" + "MyPriority.prototype = {" + " _priority: null," + " get priority() { return this._priority; }," + " set priority(aValue) { this._priority = aValue; }," + " adjustPriority: function(aDelta) {" + " this._priority += aDelta;"+ " }," + " QueryInterface: function(aIID)" + " { " + " /*if (!aIID.equals(nsISupportsPriority) && "+ " !aIID.equals(nsISupports))"+ " throw Components.results.NS_ERROR_NO_INTERFACE;*/"+ " return this;"+ " }" + "};" + "" + "var MyPriorityFactory = {" + " createInstance: function (aOuter, aIID)" + " { " + " if (aOuter != null)"+ " throw Components.results.NS_ERROR_NO_AGGREGATION; "+ " return (new MyPriority()).QueryInterface(aIID);"+ " }" + "};" + "" + "var MyPriorityModule = {" + " _firstTime: true," + " registerSelf: function(aCompMgr, aFileSpec, aLocation, aType)" + " {" + " aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);"+ " aCompMgr.registerFactory(CLASS_ID, CLASS_NAME, CONTRACT_ID, MyPriorityFactory);"+ " }," + "" + " unregisterSelf: function(aCompMgr, aLocation, aType)" + " {" + " aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);"+ " aCompMgr.unregisterFactoryLocation(CLASS_ID, aLocation); "+ " }," + "" + " getClassObject: function(aCompMgr, aCID, aIID)" + " {alert('hi');" + " if (!aIID.equals(Components.interfaces.nsIFactory))"+ " throw Components.results.NS_ERROR_NOT_IMPLEMENTED;"+ "" + " if (aCID.equals(CLASS_ID))"+ " return MyPriorityFactory;"+ "" + " throw Components.results.NS_ERROR_NO_INTERFACE;"+ " }," + "" + " canUnload: function(aCompMgr) { return true; }" + "};" + "MyPriorityModule.registerSelf(reg);" + ""; // Create temp file to load var tempfilename = Path.GetTempFileName(); tempfilename += ".html"; using (TextWriter tw = new StreamWriter(tempfilename)) { tw.WriteLine(intialPage); tw.Close(); } browser.Navigate(tempfilename); browser.NavigateFinishedNotifier.BlockUntilNavigationFinished(); using (var context = new AutoJSContext(GlobalJSContextHolder.BackstageJSContext)) { string result = String.Empty; var success = context.EvaluateScript(initialjavascript, out result); Console.WriteLine("success = {0} result = {1}", success, result); } File.Delete(tempfilename); // Create instance of javascript xpcom objects var p = Xpcom.CreateInstance <nsISupportsPriority>("@mozillazine.org/example/priority;1"); Assert.NotNull(p); // test invoking method of javascript xpcom object. Assert.AreEqual(20, p.GetPriorityAttribute()); Xpcom.ComponentRegistrar.UnregisterFactory(ref aClass, factory); }
public Folge getDownloadLinks(Folge SelectedFolge) { foreach (KeyValuePair <string, string> host in SelectedFolge.HosterandLink) { MyWebBrowserClone.Load(SelectedFolge.FolgenURL + host.Key); while (MyWebBrowserClone.thsi.IsBusy) { ; } MyWebBrowserClone.DocumentText = ""; while (MyWebBrowserClone.GetDocument() == "") { ; } string help2 = ""; MyWebBrowserClone.thsi.Invoke((MethodInvoker) delegate() { using (AutoJSContext context = new AutoJSContext(MyWebBrowserClone.thsi.Window)) { context.EvaluateScript(@"if (true) { s = '6LeiZSYUAAAAAI3JZXrRnrsBzAdrZ40PmD57v_fs' var t2 = $('section.serie .hoster-player').data('lid'); document.getElementsByTagName('body')[0].innerHTML = '<div id=""challenge""></div>'; function t(e) { 0 < t2 && $.ajax({ url: 'ajax/embed.php', type: 'POST', dataType: 'JSON', data: { LID: t2, ticket: e }, success: function(e) { document.getElementsByTagName('html')[0].innerHTML = e.link; }, error: function() { document.getElementsByTagName('html')[0].innerHTML = 'Failed'; } }) } 0 < s.length ? (void 0 === series.grendered && (grecaptcha.render('challenge', { sitekey: s, size: 'invisible', callback: t }), series.grendered = !0), grecaptcha.execute()) : t('') }", out help2); } }); MyWebBrowserClone.Bringtofront(); if (Settings.Default.AutoSolve) { BypassGoogleCaptcha bypass = new BypassGoogleCaptcha(MyWebBrowserClone.thsi, SelectedFolge.FolgenURL + host.Key); bypass.GetVideoLink(); } string DirectLink = ""; if (host.Key == "vivo") { while (!MyWebBrowserClone.GetDocument().Contains("vivo.sx/")) { Thread.Sleep(1000); } DirectLink = "https://vivo.sx/" + MyWebBrowserClone.GetDocument().Split(new string[] { "vivo.sx/" }, StringSplitOptions.RemoveEmptyEntries)[1].Split('<')[0]; } else if (host.Key == "VeryStream") { while (!MyWebBrowserClone.GetDocument().Split(new string[] { "hoster-player" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new string[] { "</div>" }, StringSplitOptions.None)[0].Contains("iframe")) { Thread.Sleep(1000); } string help = MyWebBrowserClone.GetDocument(); help = help.Split(new string[] { "hoster-player" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new string[] { "<iframe " }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new string[] { "src=\"" }, StringSplitOptions.RemoveEmptyEntries)[1].Split('\"')[0]; LinkExtractors.VeryStreamExtractor vsd = new LinkExtractors.VeryStreamExtractor(); DirectLink = vsd.GetDirectVideoLink(help); vsd.Destroy(); vsd = null; } MyWebBrowserClone.Sendtoback(); SelectedFolge.HosterandLink[host.Key] = DirectLink; break; } return(SelectedFolge); }