Reputation: 221
I am new bee of the automation testing. On my code, I am using the JavaScript on my Selenium automation test script (on using the JUnit). I am trying to find the current window title:
driver = new ChromeDriver();
js = (JavaScriptExecutor)driver;
driver.get(//passed url);
//after the log in my Org. I execute the command below
//to get the title of the current window I execute the below command
js.executeScript("document.getElementsByTagName('title').innerHTML;");
But the above command will return the answer as the null instant of getting the title of the window. So does anyone know what's wrong with my command?
But I get the title of the window on executing on the console log of the page. So I don't know what's wrong with my code.
Thanks.
Mohan Raj S.
Upvotes: 0
Views: 5562
Reputation: 1868
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = js.executeScript("return document.title;").toString();
Upvotes: 0
Reputation: 9
You could do it like this also
function titleCheck() {
promise = driver.getTitle();
promise.then(function(title) {
console.log("The title is: " + title);
});
}
reference: https://blog.testproject.io/2018/03/08/selenium-javascript-best-practices/
though their var test- stuff doesn't work for me I had to remove it.
Upvotes: 1
Reputation: 5347
Change the following line:
document.getElementsByTagName('title').innerHTML
to:
return document.getElementsByTagName('title')[0].innerHTML
in code it will be:
js.executeScript("return document.getElementsByTagName('title')[0].innerHTML;");
getElementsByTagName returns array of elements. So we need to pass the index value.
Web driver interface provides get title method. It is very simple.
String title=driver.getTitle();
System.out.println("Title is" + title);
Upvotes: 2