Inject a combination of HTML and JavaScript code into the Selenium Webdriver

I am facing a challenge where I have an HTML document stored in memory as a string, and it includes a <script> tag with a script that manipulates the DOM. My goal is to load this HTML page into Selenium WebDriver and retrieve the modified version after the script has taken effect. However, I am reluctant to write the HTML to a file and then load it using

driver.get("file://path/to/file")
. So, my question is whether there is another way to achieve this without writing to a file.

If WebDriver cannot handle this task, are there any alternative solutions available?

Let's consider the following example:

<html><head>
<script type="text/javascript">
function fill(){
    var i = "secret"
    document.forms[0].elements[1].value=i
}
</script>
</head><body onload="fill()">
<form method="POST"><input type="hidden" name="he1" value="">
<input type="hidden" name="he2" value="">
</form></body></html>

The desired outcome is for the WebDriver to execute the script and update the form accordingly.

Note: The provided example is simplified; the actual script I need to run is much more complex.

Answer №1

If you prefer not to go through the hassle of creating a file or loading a URL in order to update the content of your page, you can utilize the Data URLs feature. This feature supports HTML, CSS, and JavaScript, allowing you to easily manipulate your page's content:

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)

Answer №2

this script allows for the loading of HTML content containing JavaScript and CSS.

encoded_html = base64.b64encode(html_content.encode('utf-8')).decode()
driver.get("data:text/html;base64," + encoded_html)

Answer №3

To start fresh, you could create an empty webpage like this:

<html></html>

Next, inject content into the page:

ChromeDriver driver = new ChromeDriver();
driver.get("file://empty-page.html");
String innerHtml = "<head>...</head><body onload="...">...</body>";
driver.executeScript("document.innerHTML = " + innerHtml);

Trigger the load event on the body:

driver.executeScript("$(document.body).trigger('load');");

Retrieve the updated HTML:

String result = driver.executeScript("document.body.innerHTML;");

Answer №4

When working with Java Selenium 2.4.2, I have a method that replaces the inner html of an existing element. To ensure proper HTML escaping for JavaScript, I utilize Apache's StringEscapeUtils.escapeJavaScript.

    public void replaceHTML(By by, String html) {
      WebElement e = driver.findElement(by);
      ((JavascriptExecutor) driver).executeScript("arguments[0].innerHTML='" + StringEscapeUtils.escapeJavaScript(html) + "'", e);
    }

Here is an example of the HTML string I passed in:

<button type="button" onclick="alert('Hello world!')">Click Me!</button>

Some additional notes:

  • I encountered issues with "Lance Java's" approach due to invalid escaped characters. Adding a single quote after the equal sign resolved this problem.

  • I also tested "Kenneth Baltrinic's" suggestion of using driver.get('about:blank'); but found that writing to the screen while interacting with the base document was challenging. In Java, I had to use double quotes like driver.get("about:blank"). This testing was done using Chrome.

Answer №5

Just a quick update: escapeEcmaScrip() now replaces escapeJavaScript() as of 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);

}

Answer №6

One possible solution is to utilize jetty embedded. By configuring a jetty instance, you can have it serve html strings stored in memory as web pages through a Servlet or Handler.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

What is the Dojo counterpart for jQuery's .live() function?

Is there a Dojo alternative to jQuery .live() function? http://api.jquery.com/live/ In my search, the only workaround I came across was to disconnect the event handlers in Dojo and then reconnect them when new dynamic content is added to the page. ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Ways to launch a new tab

Robotic operation initiated: Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_T); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_T); ArrayList<String> openedTabs ...

The ng-repeat function is failing to show any data on the HTML view, instead only displaying a row for each property present

HTML Code: <div ng-repeat="addr in addrShipData"> <input type="radio" name="resp1" ng-checked='true'/> {{addr.addressLine1 +","+addr.addressLine2+", "+addr.city+ ","+addr.state+", "+addr.country+", "+addr.zipCode+","+addr ...

Avoid requesting Chrome Camera permission if it has already been granted during a previous WebRTC call

Our web-conference application utilizes a Flash client for video and audio communication. Video is handled through the Red5 Media Server, while audio is managed using WebRTC. When attempting to access the microphone or camera in Flash, users are required ...

Transforming a React application from ES6 hooks to Class-based components

Hello, I am new to React and currently facing a challenge in converting the following code into a Class Based Component. Despite knowing that I am going in the opposite direction, I am unable to figure out how to proceed without encountering errors. Any ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Can you explain the correct folder configuration for a SpringBoot project that incorporates static files?

I'm having trouble figuring out why my SpringBoot web application isn't displaying in the browser. Here's what my debug log is showing: 2017-08-04 14:54:24.760 DEBUG 23863 --- [tp1027569178-15] o.s.w.servlet.view.InternalResourceView : For ...

The combination of a modal box, checkbox, and cookie feature creates

I am trying to accomplish the following tasks: When the homepage loads, I want a modal box to appear Inside the modal box, there should be a form with a mandatory checkbox After checking the checkbox, submit the form and close the modal box to return to ...

Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart. The project includes various categories with different products within each category. When adding a product to the cart from one category, it displays correctly. Likewise, adding anot ...

Determining the Count of Prime Numbers within a Range

public static void main(String[] args) { int a = 0; System.out.println(System.currentTimeMillis()); for(int x = 2; x <=10000; x++) { boolean hasDivisor = false; for(int y = 2; y < x; y++) { ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

Problem with traversing from parent to children elements using jQuery selectors

<form data-v-c4600f50="" novalidate="novalidate" class="v-form"> <div data-v-c4600f50="" class="pr-2" question="Top Secret4"> <div data-v-c4600f50="" f ...

Obtain the most recent day on the calendar using WebDriver

I am trying to determine the last day of the current month on a calendar. You can see the screenshot here. Below is the HTML code snippet: <table class="ui-datepicker-calendar"> <thead> <tbody> <tr> < ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...

Assistance required in filling out a table solely through JavaScript with input from an HTML form

Hello, I am currently pursuing a second career and have just started learning HTML & JavaScript. For a simple assignment, I need to take user input in the form of numShares and numYears through HTML. My goal is to use JavaScript to populate a 3-column tabl ...