I have a html document in memory as a string. It contains a tag with a little script that manipulates the dom. I now want to load that html page
Just a small update: escapeEcmaScrip() replaces escapeJavaScript() in 2015.
public static void main(String[] args) throws InterruptedException{
driver = new FirefoxDriver();
driver.get("http://dhtmlx.com/docs/products/dhtmlxTree/");
replaceHTML(By.xpath("//*/span[text()='Supported browsers:']"), "<button type=\"button\" onclick=\"alert('Hello World!!')\">Click Me!</button>");
}
private static void replaceHTML(By by, String html) {
WebElement e = driver.findElement(by);
((JavascriptExecutor) driver).executeScript("arguments[0].innerHTML='" + StringEscapeUtils.escapeEcmaScript(html) + "'", e);
}
Using Java Selenium 2.4.2 I use the following to replace inner html of an existing element. I use the Apache StringEscapeUtils.escapeJavaScript to escape the HTML because this is a JavaScript replace of the inner html.
public void replaceHTML(By by, String html) {
WebElement e = driver.findElement(by);
((JavascriptExecutor) driver).executeScript("arguments[0].innerHTML='" + StringEscapeUtils.escapeJavaScript(html) + "'", e);
}
Example html String I passed in.
<button type="button" onclick="alert('Hello world!')">Click Me!</button>
Notes:
I couldn't get "Lance Java's" approach to work because of invalid escaped characters. Adding a single quote after the equal sign fixed this problem.
I tested "Kenneth Baltrinic's" suggestion of using driver.get('about:blank'); but I wasn't able to write to the screen interacting with the base document. In java I had to use double quotes driver.get("about:blank"). I tested this with Chrome.
If you don't want to create a file or load a URL before being able to replace the content of the page, you can always leverage the Data URLs feature, which supports HTML, CSS and JavaScript:
ChromeDriver driver = new ChromeDriver();
html_content = """
<html>
<head></head>
<body>
<div>
Hello World =)
</div>
</body>
</html>
"""
driver.get("data:text/html;charset=utf-8," + html_content)
You could load an empty page eg:
<html></html>
And then set it's innerHTML
ChromeDriver driver = new ChromeDriver();
driver.get("file://empty-page.html");
String innerHtml = "<head>...</head><body onload="...">...</body>";
driver.executeScript("document.innerHTML = " + innerHtml);
Then fire the load event on the body
driver.executeScript("$(document.body).trigger('load');");
Then get the resultant HTML
String result = driver.executeScript("document.body.innerHTML;");
You could fire up jetty embedded. The jetty instance could then serve in memory html strings as web pages via a Servlet / Handler.