Selenium does not load external JavaScript files

I attempted to inject external JavaScript code into Selenium Webdriver by modifying the DOM. Here is the code snippet I used for this:

public class Testing extends BaseInitialization{

public static void main(String args[]) {
    new Testing();
}

public Testing() {
    driver.get("http://www.google.com/");
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    jse
            .executeScript("var s=window.document.createElement('script');" +
                    " s.type = 'text/javascript'; s.src='elementController.js';" +
                    " window.document.head.appendChild(s);");
    jse.executeScript("test();");
}
}

The corresponding JavaScript file looks like this:

document.ourFunction =  function(){
     alert("Hey");
}

function test() {
     alert(1);
}

This image shows a snippet of my project structure where the JS file is located at the same level as the Testing class:

https://i.sstatic.net/vxfIh.png However, despite the injection process seeming to work, the external JavaScript file does not load properly. If I replace the source file name with direct JavaScript code (e.g., an alert), it works fine. But when I try to use the contents from the JS file, it fails. Can you identify what mistake I might be making?

Answer №1

It is crucial to insert the script node into the head node, as this action prompts the browser to execute the JavaScript contained within the script node or in an external src file.

The following code successfully ran on my Chrome browser, triggering an alert with the text "test".

public void aa() throws InterruptedException {

String script = 
        "var head= document.getElementsByTagName('head')[0];" +
        "var script= document.createElement('script');" +
        "script.type= 'text/javascript';" +
        "script.src= 'test.js';" +
        "head.appendChild(script);";

driver.get("file:///C:/workspace/js-projects/tey/reports/cucumber_report.html");
Thread.sleep(3000);

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(script);

Thread.sleep(3000);
js.executeScript("test()");

Thread.sleep(10000);
}

Contents of test.js

function test() {
    alert('test');
}

Answer №2

After further consideration, I have decided to revise my initial answer. It appears that the issue with the input lies in its attempt to access an external location from the google server. However, upon utilizing the Scanner class to generate a JavaScript string and directly appending it to s.src, the functionality seems to improve.

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

I am trying to utilize a cookie to retrieve the current month, date, and time. Unfortunately, the information is not displaying properly and the date is showing up as

I'm facing an issue with the code snippet below. I keep receiving an undefined error in this specific line of code: `var datemsg = nameOfMonths[date.getMonth()] + " " + date.getDate();`. When I simply use var date = new Date();, the values are succes ...

How do I load a JSON response into an array using JQuery and AJAX?

Can anyone help me figure out why I'm only getting "undefined" in the alert box when I try to run this code? I want to populate the array outside of the .ajax function. $(document).ready(function() { var reviewArray = new Array(); getReview ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

a problem with the display toggling feature in VueJS regarding the "Show more" / "Show less"

Hey everyone, I am currently working on a filter feature using VueJS and Laravel. I'm facing some challenges with the (Show more) / (Show Less) button functionality. The issues are: Issue 1: Normally when you limit a list of items, it should show a "S ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

Utilizing AngularJS in combination with Bootstrap's user-friendly UI date

Is there a way to manipulate the datepicker object so it can open and close as needed? Also, how can I access the datepicker object in a different directive within AngularJS? ** HTML ** <input type="text" class="form-control" uib-datepicker-popup="{{f ...

Choosing an asp.net RadioButton using javascript in the presence of autopostback

Here is the scenario: There are multiple radio buttons with a specific GroupName and AutoPostBack="true". For the purpose of styling, the radio button is hidden using JavaScript and the click on its container (a td) is managed through JavaScript. When th ...

Interrupt program execution using express.js

Is there a better way to interrupt the program flow and redirect to a specific route? I'm looking for something like a header redirection but using route names instead of the full URL. This functionality is common in PHP frameworks and can be quite p ...

Eliminate forward slashes in MySQL queries within a Node.js environment

Here is the code snippet that I am working with. pool.getConnection(function (err, connection) { connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " and fileName ...

Can you suggest a more efficient approach to optimizing these angular bindings?

I integrated a form into a view within my Angular JS 1.2.6 application. <div class="container" ng-controller="LoginCtrl as signin"> <div class="row"> <div class="col-md-4"> <form name="signin.myForm" novalidate autocomplete="off" ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Exploring the Implementation of itemClickListener in Spinner on Android

Within my application, I am utilizing a Spinner to display data retrieved from a server. The data from the server includes: "sections": [{ "id": 1, "name": "Item 1" }, { "id": 2, "name": "Item 2" ...

Can you provide the regular expression that will successfully match this specific string of text?

Can you solve this fruit riddle? apple is 2kg apple banana mango is 2kg apple apple apple is 6kg banana banana banana is 6kg If the fruits are limited to "apple", "banana", and "mango", how can we write a regex that extracts the names of ...

Click handler fails to trigger on dynamically rendered elements through Ajax Callback, limited to Safari browser only

I'm facing an issue with getting a feature to work on Safari and iOS devices, even though it works perfectly on Firefox, Chrome, Edge, and IE. The problem arises with an input field on the page that sends user input to the server and updates the DOM ...

Struggling to update local state with response data when utilizing hooks in React

I am a beginner using Functional components and encountering an issue with setting the response from an API to a local useState variable. Despite receiving the response successfully, the variable remains empty and I am struggling to figure out how to resol ...

conceal the bootstrap navigation bar while the page is being

Struggling to toggle a Bootstrap navbar on scroll? Need some guidance from the pros out there. I admit, my Bootstrap and jQuery skills are pretty basic. The browser console doesn't throw any errors, and I've experimented with fadeIn, fadeOut, add ...

How to execute a function in a child process using node.js?

In my node.js application, I am receiving a file through a web request and need to perform a time-consuming conversion process on it. To prevent this task from affecting the main thread's performance, I currently have it triggered by a setTimeout() ca ...

Ensure that only the dropdown menu that is clicked within a Vue loop opens

Hey, I'm having an issue with my dynamically created drop-down menus. I can display them correctly using v-Show, but the problem is that when I click on one element, they all open below my code. <div :class="{inizio : utenteAttivo.nome === con ...

What is the optimal method for extracting information from a raw date represented as a sequence of numbers in Java?

Providing my raw date as "20231110" Presenting my solution in code: private String transformRawSwiftDate(String rawDate) { // year = 0,4 - month 4,6 - day - 6,lastIndex return new StringBuilder().append(rawDate.substring(0, 4)) .append ...