We can replace inner html of any element existing on the page.
To do this we should use JavascriptExecutor
and execute a script.
In general Java code looks just like this
String script = "arguments[0].innerHTML='" + StringEscapeUtils.escapeEcmaScript(innerHtml) + "'";
((JavascriptExecutor) driver).executeScript(script, webElement);
Modify text of element
Let’s try to implement this 2 steps scenario with Selenium WebDriver
1. Get to www.google.com
driver.get("http://www.google.com");
2. Replace the Gmail link’s text (top-right corner) with Hotmail
WebElement webElement = driver.findElement(By.linkText("Gmail"));
String script = "arguments[0].innerHTML='Hotmail'";
((JavascriptExecutor) driver).executeScript(script, webElement);
What links/pages on the Internet would you modify? :)
Replace page’s content
Using the same approach we can replace the content of the page with html from a file. Let’s implement that.
The file should be saved in the resources
folder.
String htmlFromFile = readFileIntoString(fileName);
WebElement e = getDriver().findElement(By.tagName("html"));
String script = "arguments[0].innerHTML='"
+ StringEscapeUtils.escapeEcmaScript(htmlFromFile) + "'";
((JavascriptExecutor) getDriver()).executeScript(script, e);
Note: See How to read file to String
You may also find these posts interesting: