switch out javaScript for selenium

I'm attempting to replace the JavaScript functionality of a web page using Selenium (in Java with Firefox Geckodriver, if that makes a difference).

Consider this webpage:

<HTML><HEAD></HEAD>
<BODY>
    <DIV id="time">Time</DIV>
</BODY>
<SCRIPT>
    !function(){
        setInterval(function(){
            document.getElementById('time').innerHTML = new Date();
        }, 500);
    }();
</SCRIPT>
</HTML>

Now, after loading it with Selenium, I am using JavascriptExecutor to remove the <SCRIPT> section.

((JavascriptExecutor) driver).executeScript(
    "var r = document.getElementsByTagName('script');" +
    "for(var i = (r.length - 1); i >=0; i--){" +
    "   r[i].parentNode.removeChild(r[i]);" +
    "}");

Then, I wait for 2 seconds and add a new <SCRIPT> element.

Thread.sleep(2000);

((JavascriptExecutor) driver).executeScript(
    "var newScript = document.createElement(\"SCRIPT\");" +
    "newScript.innerHTML = \"document.getElementById('time').innerHTML = 'NEW SCRIPT IS RUNNING';\";" +             
    "document.body.appendChild(newScript);");

It appears to be working, but the old script is still active and updating the <DIV> tag with the current time. So, I am looking for a way to stop the active JavaScript threads or instruct Selenium to 'soft' reload the page with the altered DOM tree.

Answer №1

Special thanks to the tip from @pguardiario for guiding me in creating a successful solution. I utilized browserMob proxy to intercept the webpage response, eliminating all <SCRIPT> tags from the HTML. This allowed the selenium web driver to inject its own JavaScript seamlessly.

String webpage = "http://SOME_WEB_PAGE.com";

// initializing proxy object
BrowserMobProxy proxy = new BrowserMobProxyServer();

// create a response filter
proxy.addResponseFilter(new ResponseFilter() {
    @Override
    public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) {
        // check if it is a response to the webpage request
        if(messageInfo.getUrl().equals(webpage)){
            // parse the result using JSOUP and remove all <SCRIPT> Tags
            Document doc = Jsoup.parse(contents.getTextContents());                     
            for(Element element : doc.select("script")) element.remove();                       
            contents.setTextContents(doc.html());
        }
    }
});

// starting the proxy and setting it as a firefox option
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);            
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
FirefoxOptions options = new FirefoxOptions();
options.merge(capabilities);

// initializing the selenium web driver and loading the modified webpage without any <SCRIPT> Tags
WebDriver driver = new FirefoxDriver(options);                       
driver.get(webpage);            
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

// injecting custom javaScript
((JavascriptExecutor) driver).executeScript(
    "var newScript = document.createElement(\"SCRIPT\");" +
    "newScript.innerHTML = \"document.getElementById('time').innerHTML = 'NEW SCRIPT IS RUNNING';\";" +             
    "document.body.appendChild(newScript);");

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

Verify element clickability without setting a specific time limit for waiting

According to the Selenium Documentation, it is advised not to mix explicit and implicit wait times: Caution: Avoid mixing implicit and explicit waits as this may result in unpredictable wait times. For instance, having an implicit wait of 10 seconds and ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

Modify the CSS styles of inner elements dynamically

Within my code, I have implemented a SplitPane and included a CSS file that contains the following styling rules: .split-pane > .split-pane-divider { -fx-padding: 0 0 0 1; -fx-background-color:-fx-background; } However, during runtime, I e ...

The compilation of debug Java with Javac in CordovaLib is not being done incrementally

I am currently in the process of setting up Ionic on my new computer, but I have encountered an issue while trying to build a Cordova Android project that I can't seem to resolve. The software and versions I am using include: NodeJS v6.9.1 npm ...

Ensuring the vue carousel component stops rendering once all of its data has been displayed

Is it possible to stop rendering a vue carousel component once its data is displayed or after a certain amount of time? I've searched for information on this, but haven't found anything relevant. Despite it being an unusual request, I still want ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Console log displays varied outputs for identical arrays

Having an array in a static form and one that is filled using the ajax post function, I initially planned to replace the static array with the dynamic one. However, upon closer inspection, it seems that the two arrays are not matching. Array 1 (static) ...

The test results differ depending on the browser used - it fails when executed in web

When a new user signs up, this code allows the process to be carried out successfully. It switches the Capybara driver to Selenium, visits the homepage, clicks on the 'Sign up' link, fills in the required information for the user, and submits the ...

"Interact with jQuery by sliding side to side or in a circular motion

I am in need of assistance with sliding images using jQuery back and forth, or making them go round in a loop. Currently, the images slide up to the last element and then swiftly return to the first div, which is not visually appealing at all. I understa ...

jQuery DataTable error: Attempted to set property 'destroy' on an undefined object

<script> $('#archiveTable').DataTable({}); </script> <table id="archiveTable" datatable="ng" class="table table-sm" style="color:black"> <!--some code--> </table> This is a snippet of HTML code Upon checking t ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

The properties are not appearing on the screen nor in the React Development Tools

Having difficulties grasping React props and mapping data from an array? Struggling to get the props to show up on your Card component, or display in React dev tools? It's unclear where the mistake lies. Seeking assistance to pinpoint the issue. Also ...

Utilize the function specified in an external file

In my project, I have a typescript file named "menuTree.ts" which compiles to the following JavaScript code: define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Menu ...

Struggling to implement sparklines for real-time data in the AngularJS adaptation of the SmartAdmin template

Currently, I am embarking on a project that involves utilizing the AngularJS version of the SmartAdmin Bootstrap template foundhere. Within this project scope, I am required to integrate sparklines into various pages. I have successfully implemented them ...

Vuetify Error - "Attempting to access 'extend' property of an undefined object"

Upon installing Vuetify, I encountered an error in the console. My webpack version is v3.6 Uncaught TypeError: Cannot read property 'extend' of undefined at Module../src/mixins/themeable/index.ts (index.ts:21) at __webpack_require__ (boo ...

Setting up language preferences without having to reload the entire page

Is there an alternative method to change the app language without refreshing the entire page? The code snippet below always refreshes the page, leading to a poor user experience. window.location.search = "sap-language=EN"; The following code snippet is a ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

Moving pictures using css3 transitions

Trying to create a straightforward image slider. Below is the provided JavaScript code: $(document).ready(function() { $('#slide1_images').on('click', 'img', function(){ $("#slide1_images").css("transform","translateX ...

Having trouble accessing the web browser with Selenium ChromeDriver on Windows 10

Trying to launch a web browser with Selenium Chromedriver on Windows 10 using Python in Jupyter notebooks via an Ubuntu terminal has proven to be quite challenging. Despite researching and attempting solutions from various Stack Overflow posts, I find myse ...