Selenium JAR test case encountered a halt when it reached JavaScript commands

While working on a test script for our company using Selenium JUnit, I encountered an issue. The script runs smoothly in my account on the company's network but encounters a roadblock when other employees try to run it, specifically when it reaches the JavaScript segment.

I realized that the locators for each Sharepoint element vary across different accounts. For example, #ctl00_PlaceHolderMain_nameInput in my account is actually #ctl01_PlaceHolderMain_nameInput in another account, making these elements unreachable through my code. How can this issue be resolved?

Our web browser of choice is Firefox, and users are required to authenticate to run the test case (HTTPS page).

Any assistance in resolving this matter would be greatly appreciated.

The snippet of the script causing trouble looks like this:


WebElement NewPage;
NewPage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#mp1_0_2_Anchor")));
NewPage.click();
Thread.sleep(5000);
// Error occurs after executing the following lines
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript(""
+ "var tBox= document.querySelector('.ms-dlgFrame').contentDocument.querySelector('#ctl00_PlaceHolderMain_nameInput');"
+ "tBox.setAttribute('value','Testcase 13.1');"
+ "var btn= document.querySelector('.ms-dlgFrame').contentDocument.querySelector('#ctl00_PlaceHolderMain_createButton');"
+ "btn.click();"
);
}

Here is the Html code for the iFrame:

<div id="s4-workspace" style="height: 175px; width: 390px; overflow-y: auto;">
<div id="s4-bodyContainer">
<div id="s4-titlerow" class="s4-pr s4-notdlg s4-titlerowhidetitle ms-titlerowborder" style="width: 372px;">
<div class="s4-title s4-lp">
<div class="s4-title-inner">
<table class="s4-titletable" cellspacing="0">
<tbody>
<tr>
<td class="s4-titlelogo">
<a id="ctl00_onetidProjectPropertyTitleGraphic" href="/en/News/" target="_blank">
<img id="ctl00_onetidHeadbnnr2" name="onetidHeadbnnr0" src="/_layouts/images/siteIcon.png" alt="News" style="border-width:0px;">
</a>
</td>
<td class="s4-titletext">
<h1 name="onetidProjectPropertyTitle">

<a id="ctl00_PlaceHolderSiteName_onetidProjectPropertyTitle" href="/sv/News/" target="_blank">News</a>

</h1>
<span id="onetidPageTitleSeparator" class="s4-nothome s4-bcsep s4-titlesep"><span><span style="height:11px;width:11px;position:relative;display:inline-block;overflow:hidden;"><img src="/_layouts/images/fgimg.png" alt=":" style="border-width:0px;position:absolute;left:-0px !important;top:-585px !important;"></span></span> </span>
<h2>

New Page

</h2>
<div class="s4-pagedescription" tabindex="0">

</div>
</td>
<td class="s4-socialdata-notif">

</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="s4-topheader2" class="s4-pr s4-notdlg">
<a name="startNavigation"></a>
<div id="s4-searcharea" class="s4-search s4-rp">

Upon referring to this resource, I was able to extract the error log below:

Error Log: JUnit version 4.12 .E Time: 44,583 There was 1 failure: 1) testId1331(ID131) org.openqa.selenium.JavascriptException: TypeError: tBox is null Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700' System info: host: 'AOS391', ip: 'xxx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_111' Driver info: org.openqa.selenium.firefox.FirefoxDriver Capabilities [{rotatable=false... Session ID: ... at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) (Further Stack Trace details omitted for brevity)

FAILURE! Tests run: 1, Failures: 1

Answer №1

Have you considered using the Selenium API in Java instead of Javascript? Try this code snippet to see if it resolves your issue:

WebElement NewPage;
NewPage= wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#mp1_0_2_Anchor")));
NewPage.click();
Thread.sleep(5000);

//An error may occur after executing the following lines

WebElement tBox = driver.findElement(By.cssSelector(".ms-dlgFrame #ctl00_PlaceHolderMain_nameInput"));
tBox.clear();
tBox.sendKeys("Testcase 13.1");
WebElement btn = driver.findElement(By.cssSelector(".ms-dlgFrame #ctl00_PlaceHolderMain_createButton"));
btn.click();

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

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...

Retrieving checkbox list values using jQuery

I am working with a div that contains some checkboxes. I want to write code so that when a button is clicked, it will retrieve the names of all the checked checkboxes. Can you provide guidance on how to achieve this? <div id="MyDiv"> .... <td> ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

What is the proper way to convert the date and time of Friday, October 23, 2015 at midnight into a specific format for a datetime string?

I'm currently utilizing the bootstrap datetimepicker and I need to retrieve the datetime and then add days to it. var get_date_time = Friday, October 23rd 2015, 12:00:00 am I want to format get_date_time to "Oct 25 2015 12:00:00 am", but I'm u ...

Tips for tidying up this web scraping dataset

I am facing a challenge in scraping data from a webpage that contains two tables with the same tag. The specific table I am interested in is labeled as "Event Timeline." Currently, the code I have retrieves the entire desired table without breaking it do ...

Sending a list via Ajax in Django

I recently executed an Ajax call successfully: $.ajax({ url:'/quespaper/intermediate_table', type:'GET', processData: false, data:{'url_link':url_link_copy,'updated ...

Accessing audio files in a directory using ajax

I need assistance with implementing a feature in my mp3 music player code. I want the player to fetch songs from a directory instead of using the page's URL. var songs = [{ { title: 'Blackout City', artist: 'Anamanaguchi&ap ...

The information sent via POST (via fetch JavaScript with PHP8) is not being received by PHP8

My PHP8 server is not receiving the data I am sending. When trying to insert a new song into my API, an error occurs and in the console, I see an object with POST as an empty array. fetch("http://localhost/api.audio-player/",{ method: 'POST&apos ...

The sheer power of my bruteforce Java machine, equipped with Selenium and WebDriver, is so lightning-fast that it struggles to properly log in even with the correct credentials

Currently, I am in the process of developing a Java brute-force machine using selenium and web-driver. The aim of the program is to prompt users for a website's login page URL, inspect element selector for username, password, and login button, and the ...

Make sure to not update until all the necessary checks have been completed successfully

My goal is to update an array of objects only after all the necessary checks have passed. I have one array of objects representing all the articles and another array of objects representing the available stock. I want to make sure that all the articles ar ...

Tips to prevent modal impacts on underlying elements?

When I click on a button, a modal pops up. However, the background contents seem to spread out and sometimes scroll automatically when the modal appears. I have searched for a solution to this issue but have been unsuccessful. Can anyone please help me ide ...

Newly inserted table columns aren't compatible with event listeners

My HTML table structure varies depending on the content of the uploaded CSV file. I have integrated a plugin called Dragtable to make the table columns draggable. Additionally, I have implemented methods to add rows and columns. Here is an example of the a ...

Ensure that the elements are visible post-click, then proceed to print the necessary elements using Selenium with Python

I'm having an issue where I want to wait for the element to be visible after a click and then print the necessary element, but it's not waiting unless I use time.sleep. I'd like to utilize WebDriverWait(driver, 20).until(EC.visibility_of_e ...

Error: The geoNear command was unsuccessful due to the presence of multiple 2d indexes

My goal is to fetch documents from a collection based on distance. I attempted to utilize the $geoNear aggregation, but encountered errors (while using node.js and Postman) or received zero records as output. Example Document: { "_id" : ObjectId("5cc ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Is there a way to identify the visible portion of the browser window as seen by the user?

Looking at the image below, you'll notice that the website displays elements "A", "B", "C", "D", and "E". However, users may only see elements "A", "B", and a small portion of element "D" within their browser window. Some users may need to scroll down ...

Steps to assign the identifier as the current index in the v-for iteration

Struggling to assign the id based on the index of a v-for loop. I attempted: <li v-for="(item, index) in items" v-bind:key="item.id"> <p>{{item.name}}</p> <input id= {{index}} type= "number"> < ...

Finding curly brackets and commas using regular expressions

Imagine a lengthy JSON string. I am aiming to identify the following section using a regular expression: }, { "@context" My current expression is yielding two results instead of one. The only variance lies in the braces with the comma preced ...

The converging of interactive and fixed routes in next JS

After developing a NextJS application and implementing its routing system, I encountered an issue with dynamic routes. Specifically, I created a route to capture URLs in the format of {base_url}/{username}/{post-slug}. However, this route is also capturi ...

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...