/// <summary> /// Waits for angular to finish its thing /// </summary> public void WaitForAngular() { if (!IgnoreSynchronization) { _jsExecutor.ExecuteAsyncScript(ClientSideScripts.WaitForAngular, _rootElement); } }
public void WaitForAngular() { if (!NotWaitForAngularCalls) { jsExe.ExecuteAsyncScript(JavaScriptScripts.JavaScriptScripts.WaitForAngular, rootElement); } }
public void ScrollElementIntoView(string obj) { var elem = _driver.FindElement(By.XPath(obj)); IJavaScriptExecutor jsExec = (IJavaScriptExecutor)_driver; jsExec.ExecuteAsyncScript("arguments[0].scrollIntoView(true);", elem); }
public void lSleep() { //Thread.Sleep in Javascript js.ExecuteAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); //This will get clicked after 5 seconds searchButton.Click(); }
private static List <string> ExecuteAsyncSearchForStringResults(IJavaScriptExecutor jsExecutor, string searchScript, IWebElement searchRoot = null) { var asyncResult = jsExecutor.ExecuteAsyncScript(searchScript, searchRoot) as ReadOnlyCollection <object>; var searchResult = asyncResult[0] as ReadOnlyCollection <object>; var error = asyncResult[1] as string; HandleInvalidResult(searchResult, error, searchScript); return(ConvertObjectCollectionToStringList(searchResult)); }
/// <summary> /// Internal resolver for async search. /// </summary> /// <param name="jsExecutor"></param> /// <param name="searchScript"></param> /// <param name="searchRoot">(optional) specify element which will be used as search root</param> /// <returns></returns> private static ReadOnlyCollection <IWebElement> ExecuteAsyncSearch(IJavaScriptExecutor jsExecutor, string searchScript, IWebElement searchRoot) { var asyncResult = jsExecutor.ExecuteAsyncScript(searchScript, searchRoot) as ReadOnlyCollection <object>; var elements = asyncResult[0] as ReadOnlyCollection <IWebElement>; var error = asyncResult[1] as string; HandleInvalidResult(elements, error, searchScript); return(elements); }
public virtual T PerformJsAsyncAndReturnElement(IJavaScriptExecutor jsExecutor, string jsExpression) { if (jsExecutor.ExecuteAsyncScript(_jsExpression) is IWebElement returnValue) { IElement element = new ElementProxy(returnValue); return((T)element); } throw new InvalidCastException($"Return value is not of type: {typeof(T).Name}"); }
/// <summary> /// Executa um comanda Assíncrono Javascript na página atual /// </summary> /// <param name="js">Código Javascript a ser executado</param> /// <param name="parametros">Argumentos do Script</param> /// <returns>O valor retornado pelo Script</returns> public object ExecutedAsyncJavascript(string js, params object[] parametros) { IJavaScriptExecutor javaScript = Driver as IJavaScriptExecutor; if (javaScript == null) { throw new NotJavascriptConvertException("Não foi possível converter o Driver em javascript."); } return(javaScript.ExecuteAsyncScript(js, parametros)); }
public void ScrollAllElementOnFixedOdds(IWebElement el) { string s = "let i = 0;while(true){let lastTitleCss='.lifestyleProduct-mob:last-child .productTitle p'; let firstT = document.querySelector(lastTitleCss).innerText; document.querySelector(lastTitleCss).scrollIntoView();await new Promise(resolve => setTimeout(resolve, 1000));if (document.querySelector(lastTitleCss).innerHTML == (firstT)){ i++;if(i >= 3){break;}}else{i = 0;}}"; //string s = "let i = 0;while(true){let firstT = arguments[0].innerText; arguments[0].scrollIntoView();await new Promise(resolve => setTimeout(resolve, 800));if (arguments[0].innerHTML == (firstT)){ i++;if (i >= 4) { break; }}}"; IJavaScriptExecutor jse = (IJavaScriptExecutor)WebDriver; try { jse.ExecuteAsyncScript(s); } catch (WebDriverTimeoutException) { } Thread.Sleep(1000); }
/// <summary> /// Executes the script. /// </summary> /// <param name="executor">The executor.</param> public virtual JavaScriptValue Execute(IJavaScriptExecutor executor) { var convertedArgs = Arguments .Select(a => a.GetArgument()) .ToArray(); var result = IsAsync ? executor.ExecuteAsyncScript(Script, convertedArgs) : executor.ExecuteScript(Script, convertedArgs); return(new JavaScriptValue(result)); }
/// <summary> /// Executes the asynchronous script. /// </summary> /// <param name="script">The script.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> public virtual JavaScriptValue ExecuteAsyncScript(string script, params JavaScriptValue[] arguments) { var convertedArgs = arguments .Select(a => a.GetArgument()) .ToArray(); var result = javaScriptExecutor.ExecuteAsyncScript( script, convertedArgs); return(new JavaScriptValue(result)); }
public static object ExecuteAsyncJavaScript(string script, params object[] args) { try { IJavaScriptExecutor JavaScriptExecutor = (IJavaScriptExecutor)DriverFactory.Instance; return(JavaScriptExecutor.ExecuteAsyncScript(script, args)); } catch (Exception ex) { throw new ApiException(String.Format("Execution failed, please validate the provided javascript :'{0}'", script), ex); } }
/// <summary> /// Asynchronously executes an arbitrary JavaScript function on the page. /// </summary> /// <returns>The object value returned by the JavaScript function.</returns> public override object Execute() { IJavaScriptExecutor javascriptDriver = Session.Driver as IJavaScriptExecutor; if (javascriptDriver == null) { throw new InvalidCommandException("Driver does not support JavaScript"); } object[] argsArray = this.ParseArguments(); object returnValue = javascriptDriver.ExecuteAsyncScript(this.Script, argsArray); returnValue = this.ParseJavaScriptReturnValue(returnValue); return(returnValue); }
/// <summary> /// Executes a JavaScript statement passed as a string /// </summary> /// <param name="script">The JavaScript to be executed</param> /// <param name="parameters">The parameters for the passed JavaScript</param> public void ExecuteAsyncJavaScript(string script, params object[] parameters) { try { IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver); js.ExecuteAsyncScript(script, parameters); Console.Out.WriteLine("Executed the sctipt '{0}'.", script); } catch (Exception ex) { if (Preferences.BaseSettings.DebugLevel == EnumConsoleDebugLevel.Human) { Console.Out.WriteLine("Could not execute the passed asynchronous JavaScript."); } HandleErrors(ex); } }
/// <summary> /// Executes JavaScript asynchronously in the context of the currently selected frame or window. /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> public object ExecuteAsyncScript(string script, params object[] args) { IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor; if (javascriptDriver == null) { throw new NotSupportedException("Underlying driver instance does not support executing javascript"); } object[] unwrappedArgs = UnwrapElementArguments(args); WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script); this.OnScriptExecuting(e); object scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs); this.OnScriptExecuted(e); return(scriptResult); }
private static bool AngularHasFinishedProcessing(this IWebDriver driver) { string HasAngularFinishedScript = @"var callback = arguments[arguments.length - 1]; var el = document.querySelector('html'); if (!window.angular) { callback('False') } if (angular.getTestability) { angular.getTestability(el).whenStable(function(){callback('True')}); } else { if (!angular.element(el).injector()) { callback('False') } var browser = angular.element(el).injector().get('$browser'); browser.notifyWhenNoOutstandingRequests(function(){callback('True')}); }"; IJavaScriptExecutor javascriptExecutor = (IJavaScriptExecutor)driver; return(Convert.ToBoolean(javascriptExecutor.ExecuteAsyncScript(HasAngularFinishedScript))); }
private object ExecuteAndGetPrivate(IJavaScriptExecutor executor, bool returnValue) { var statement = StatementWithArguments(returnValue); var executeTemplate = returnValue ? Return_Template.ToFormat(statement) : Void_Template.ToFormat(statement); var script = ScriptWithoutJQueryCheck(executeTemplate); if (CheckForJQuery) { script = ScriptWithJQueryCheck(executeTemplate, JQueryCheckCount, JQueryCheckInterval); } var result = executor.ExecuteAsyncScript(script, Arguments.Cast <object>().ToArray()); CheckForReferenceError(result); return(result); }
//Go to Product Page, //Error: stale element reference: element is not attached to the page document public ProductPage ClickProductPage() { Driver.WaitForElementExist( By.XPath("//div[contains(text(),'Products')]"), 10); try { var LinkProductsNew = Driver.driver.FindElement(By.XPath("//div[contains(text(),'Products')]")); IJavaScriptExecutor executor = (IJavaScriptExecutor)Driver.driver; executor.ExecuteAsyncScript("arguments[0].click();", LinkProductsNew); } catch (Exception e) { Console.WriteLine(e); throw; } //等待url栏中出现product while (!Driver.driver.Url.Contains("product")) { Thread.Sleep(200); } return(new ProductPage()); }
//Wait for Angular Load public void waitForAngularLoad() { IJavaScriptExecutor jsExec = (IJavaScriptExecutor)_driver; String angularReadyScript = @"var callback = arguments[arguments.length - 1]; var el = document.querySelector('html'); if (!window.angular) { callback('False') } if (angular.getTestability) { angular.getTestability(el).whenStable(function(){callback('True')}); } else { if (!angular.element(el).injector()) { callback('False') } var browser = angular.element(el).injector().get('$browser'); browser.notifyWhenNoOutstandingRequests(function(){callback('True')}); }"; //Wait for ANGULAR to load Boolean angularLoad = Convert.ToBoolean(jsExec.ExecuteAsyncScript(angularReadyScript)); }
public object ExecuteAsyncScript(string script, params object[] args) { object result = null; IJavaScriptExecutor javaScriptExecutor = this.driver as IJavaScriptExecutor; if (javaScriptExecutor == null) { throw new NotSupportedException("Underlying driver instance does not support executing JavaScript"); } try { object[] args2 = EventFiringWebDriver.UnwrapElementArguments(args); WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script); this.OnScriptExecuting(e); result = javaScriptExecutor.ExecuteAsyncScript(script, args2); this.OnScriptExecuted(e); } catch (Exception thrownException) { this.OnException(new WebDriverExceptionEventArgs(this.driver, thrownException)); throw; } return(result); }
private static bool ExecuteWaitUntilNotPresent(IJavaScriptExecutor jsExecutor, string searchScript, string bbSeekerSearchExpression) { var asyncResult = jsExecutor.ExecuteAsyncScript(searchScript) as ReadOnlyCollection <object>; var isNotPresent = asyncResult[0] as bool?; if (asyncResult[1] is string error) { StdoutScript(searchScript); throw new ApplicationException("Error occured during BBSeeker search: '" + error + "'"); } if (isNotPresent == false) { StdoutScript(searchScript); throw new TimeoutException("Timed out waiting for element to be removed: '" + bbSeekerSearchExpression + "'."); } if (isNotPresent == null) { StdoutScript(searchScript); throw new ApplicationException("Unexpected state occured in the async waitForElementNotPresent script, returned value is null." + "This should not happen and might be a script author's error."); } return(isNotPresent.Value); }
private static string RunJavaScriptAsync(ChromeDriver ngDriver, string JS) { IJavaScriptExecutor js = ngDriver as IJavaScriptExecutor; return((string)js.ExecuteAsyncScript(JS)); }
/// <summary> /// Executes JavaScript asynchronously in the context of the currently selected frame or window. /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> public object ExecuteAsyncScript(string script, params object[] args) { return(jsExecutor.ExecuteAsyncScript(script, args)); }
private object GetAssertionFor(object credentialId) { return(jsDriver.ExecuteAsyncScript( "getCredential([{" + " \"type\": \"public-key\"," + " \"id\": Int8Array.from(arguments[0])," + "}]).then(arguments[arguments.length - 1]);", credentialId)); }
public void ShouldNotTimeoutIfCallbackInvokedImmediately() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"); Assert.That(result, Is.InstanceOf <long>()); Assert.That((long)result, Is.EqualTo(123)); }
//비동기적 실행 (driver, 자바스크립트) private void ExecuteAsyncScript(IJavaScriptExecutor driver, string script) { IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteAsyncScript(script); }
public async Task ShouldNotTimeoutIfCallbackInvokedImmediately() { await driver.GoToUrl(ajaxyPage); object result = await executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"); Assert.That(result, Is.InstanceOf <long>()); Assert.That((long)result, Is.EqualTo(123)); }
public void InjectAndExcecute(string arg) { IJavaScriptExecutor javaScriptExecutor = (IJavaScriptExecutor)driver; javaScriptExecutor.ExecuteAsyncScript(arg); }
private static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; ChromeOptions options = new ChromeOptions(); //options.AddArgument("--headless"); //options.AddArgument("--disable-gpu"); options.AddArgument("--window-size=1600,900"); options.AddArgument(@"user-data-dir=C:\Chrome-Profile"); IWebDriver driver = new ChromeDriver(options); IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver; driver.Navigate().GoToUrl("https://www.linkedin.com/in/ren%C3%A9-secher-3754003a/"); //TakeScreenshot(driver); //Thread.Sleep(10000); const string email = "*****@*****.**"; const string password = "******"; IWebElement emailInput = null; try { emailInput = driver.FindElement(By.Id("login-email")); } catch (NoSuchElementException) { //element not found } if (emailInput != null) { emailInput.SendKeys(email); IWebElement passwordInput = driver.FindElement(By.Id("login-password")); passwordInput.SendKeys(password); //TakeScreenshot(driver); passwordInput.Submit(); //Thread.Sleep(1000); //TakeScreenshot(driver); driver.Navigate().GoToUrl("https://www.linkedin.com/in/abildskov/"); } //Thread.Sleep(1000); //TakeScreenshot(driver); for (int i = 1; i <= 5; i++) { jsExecutor.ExecuteScript($"window.scrollTo(0, {i * 900});"); Thread.Sleep(100); } jsExecutor.ExecuteAsyncScript(loadJQueryScript); jsExecutor.ExecuteAsyncScript(expandMainScript); jsExecutor.ExecuteAsyncScript(expandAllScript); //TakeScreenshot(driver); Dictionary <string, object> dictionary = (Dictionary <string, object>)jsExecutor.ExecuteAsyncScript(getDataScript); Console.WriteLine("----------------------------------------------------------------------------"); Console.WriteLine(JsonConvert.SerializeObject(dictionary, Formatting.Indented)); Console.WriteLine("----------------------------------------------------------------------------"); //File.WriteAllText(@"D:/json_1.json", JsonConvert.SerializeObject(dictionary, Formatting.Indented)); //driver.Quit(); //Thread.Sleep(100000); //System.Diagnostics.Process.Start("D:/screenshot_1.png"); }
public static void ExecuteAsyncJavaScript(string script) { IJavaScriptExecutor executor = ((IJavaScriptExecutor)DriverFactory.Instance); executor.ExecuteAsyncScript(script); }