1

My aim is to change the DOM of a page before the DOMContentLoaded event. Let's say my JS would look like the code below and I want to change a value of an element:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("Value of element foo: " + document.getElementById('foo').value);
});

I know to change the DOM with the JavascriptExecutor of Selenium WebDriver, but I'm missing how to get it to to execute right before 'DOMContentLoaded' (and maybe that's not the right approach).

// some hook or whatever to execute right before 'DOMContentLoaded' or wherever suitable
((JavascriptExecutor) webDriver).executeScript("document.getElementById('foo').value='hi there'");
Prophet
  • 32,350
  • 22
  • 54
  • 79
user871611
  • 3,307
  • 7
  • 51
  • 73

1 Answers1

1

In order to do that you will have to set the pageLoadStrategy from default normal to none.
This will pass the control to the next code line immediately after launching the page with driver.get() method without waiting for the page content to be loaded.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • Seems like the only way to achieve this. One more question: Wouldn't I be in competition with the the eventListener of the calling page, since I would have to also wrap my DOM changing task in an eventListener: `((JavascriptExecutor) driver).executeScript("document.addEventListener(\"DOMContentLoaded\", function(event) { document.getElementById('foo').value='hi there'; });");` – user871611 Mar 21 '22 at 12:35
  • As about the additional question - I really do not know, I'm sorry. I would help you if I could but I don't know... You are welcome to ask a new question about that, maybe someone will be able to help there. – Prophet Mar 21 '22 at 12:38