How to use JavaScript using selenium ?
In order to locate web page So, to
Below are commands using javascript:
WebDriver driver = new ChromeDriver();
JavascriptExecutor je=(JavascriptExecutor)driver;
//navigates to je.executeScript("window.location = 'http://www.facebook.com'");
//to get url
je.executeScript("return document.URL"); //https://www.facebook.com/
//to get domain
je.executeScript("return document.domain");//return facebook.com
//to get title of page
je.executeScript("return document.title"); // Facebook – log in or sign up
//To enter text in fields
je.executeScript("document.getElementById('lst-ib').value = \"keeplearning\";");//keeplearning text is entered
(or)
je.executeScript("document.getElementById('lst-ib').value='enter value here'");//enter value here text is entered
//To click an web element
WebElement e=driver.findElement(By.id("ui-id-1"));
je.executeScript("arguments[0].click();",e);
je.executeScript("arguments[0].click();",e);
//scrolled to particular web element
WebElemente=driver.findElement(By.id('q'));
je.executeScript("arguments[0].scrollIntoView();",e);
##Depending on (x,y) x-axis and Y-axis, page will be scrolled
##example:: scrollBy(X,Y)
//scroll to the Bottom of the Web Page
je.executeScript("window.scrollTo(0,document.body.scrollHeight)");
//scroll to top of page
je.executeScript("window.scrollTo(document.body.scrollHeight,0)");
//scroll horizontally in the right direction
je.executeScript("window.scrollBy(2000,0)");
//scroll horizontally in the left direction
je.executeScript("window.scrollBy(-2000,0)");
//scroll at a particular coordinate on a web page
je.executeScript("window.scrollBy(200,300)");
//navigates to previous page using browser back button
je.executeScript("window.history.go(-1)");
#go(0) -- will refresh the current web page
#go(-2) -- will clicks browser back button 2 times
#go(-2) -- will clicks browser back button 2 times
//navigates to forward pages using browser forward button
je.executeScript("window.history.forward(-1)");
#forward(-2) -- will clicks browser forward button 2 times
//appends text to url
je.executeScript("window.location = '/search' ");//it will appends to url and redirect to that page
//To get alert
je.executeScript("alert('hello world');");
Please comment below to feedback or ask questions.
//To get the Innertext of web page
je.executeScript("return document.documentElement.innerText");
Please comment below to feedback or ask questions.
Please provide more information on javascript with selenium
ReplyDelete