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

Concealing the TinyNav Drop-Down Menu

Currently, I am utilizing TinyNav on my website and it is working wonderfully. However, due to our extensive menu system, the tinynav dropdown appears quite large. I have been attempting to figure out a way to hide all sub-menus without success. I experim ...

What is the best way to import my json information into an HTML table and customize the rows as radio buttons using only Javascript?

I am facing an issue with processing a JSON response: var jsondata = dojo.fromJson(response); There is also a string that I am working with: var jsonString = jsondata.items; The variable jsonString represents the JSON data in the file: jsonString="[ ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels. items = [ {'type': 2, 'priority': 1, 'name': 'one'}, {'type': 1, 'priority': 2, 'na ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

The sendKeys command in WebDriver is failing to enter text into the Password field

Currently, I am delving into the world of selenium webdriver automation and have encountered an issue with the sendKeys command not working on Password type fields. After doing some research online, it seems like others are also facing the same problem but ...

Instructions for launching a web browser within an Azure Function app on a Linux platform using Python programming language

I recently developed an Azure Function app that utilizes Python code. The primary function of my code is to scrape data from TripAdvisor's website, so I integrated Selenium to open a browser and extract the necessary information. While everything work ...

Transforming data from an HTML table into a MySQL database

Is there a way to transfer data from an HTML table created with JavaScript to a SQL database? I have been experimenting with the addRow(tableID) function but it doesn't seem to work. Any suggestions on how to solve this issue? Below is the code snipp ...

Adding a unique value to an array using JQuery when it does not already exist

In need of assistance with a function that is supposed to add values to an array if they do not already exist. var category_json = new Array(); $.ajax({ type: 'POST', url: "<?php ech ...

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

What is the reason behind Selenium's inability to locate XUL buttons?

I have been working on automating tests for a Firefox add-on using Selenium, specifically the insecure-links-highlighter add-on. However, I am facing an issue where it cannot locate the "Preferences" button in about:addons: extensionEntry.findElement(By.c ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

Tips for saving styled text in an Oracle database and retrieving it as JSONContentType: Application/JSON

Is there a built-in functionality in Oracle that allows for storing rich text? I have added HTML tags to formatted text and want to know the correct way of saving it in the database. Upon fetching the stored text in a resultset, I am converting it to JSON ...

Encountering difficulty in generating a new service, specifically ChromeDriverService, when initializing GRID via SSH, however the process runs smoothly when GRID is established directly

Our testing and execution operations rely on a Windows Server 2012 R2 VM where we utilize .bat scripts to set up a Selenium Enterprise Grid Hub and a Chrome Node. Interestingly, when I execute the setup for the Grid and Node by directly logging in to the ...

After the table finishes loading, my goal is to display an export to Excel button

I am currently working on generating an HTML table using JSON data received from the backend Java application. My objective is to display an "Export to Excel" button after populating the table. The process involves users entering dates and selecting option ...

Is there a way to get around the annoying "Flash Camera and Microphone Access" pop-up that appears when using Pepper/PPAPI Flash in Chrome with Selenium?

Chrome has compatibility with two versions of Flash: NPAPI and PPAPI (Pepper). These implementations handle camera and microphone permissions differently. Specifically, PPAPI (Pepper) does not seem to recognize previously granted permissions. With NPAPI, ...

What is the proper way to place the authorization header for a background image using the url()

I am currently working on fetching background images through a REST API. However, in order to successfully retrieve these images, I have to go through an authorization process. The token required for authorization is already present in the context where ...

Pressing the Google Scholar Button using Scrapy

I have been experimenting with web scraping data from Google Scholar using the scrapy library, and here is my current code: import scrapy class TryscraperSpider(scrapy.Spider): name = 'tryscraper' start_urls = ['https://scholar.googl ...

What methods can I implement to ensure a button illuminates only when correct information is provided?

I have developed a calculator for permutations and combinations. When either permutation or combination is selected, and the required values are entered, I want the calculate button to light up. How can I achieve this without using setInterval in my curren ...

The function of window.location is not responsive when used in conjunction with an ajax

The main page redirect occurs in 2 scenarios: When the user clicks logout When the session expires Code for logout functionality: $("#logoutLink").click(Logout); function Logout() { $.post("Logout", { antiCSRF: '{{acsrf}}&apo ...