Executing JavaScript in Page Object Model

When working on my automation script using Java with Selenium and the Page Object Model, I sometimes find it necessary to utilize Javascript Executor. This is because default WebDriver clicks can result in exceptions when elements are not found.

Within the framework's page where web elements are initialized, the code appears as follows:

public class MainPage {

    WebDriver driver;
    JavascriptExecutor executor = (JavascriptExecutor) driver;


    @FindBy(xpath = "//*[@id='main_button']/div/span")
    WebElement mainButton;

    @FindBy(xpath = "//*[@id='login_button']/div/span")
    WebElement loginButton;

    // constructor initializes the elements
    public MainPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    // method for clicking mainButton using WebDriver
    public void clickMainButton() {
        WebDriverWait wait = new WebDriverWait(driver, 40);
        wait.until(ExpectedConditions.elementToBeClickable(mainButton)).click();
    }

    // method for clicking loginButton using JS Executor
    public void clickLoginButton() {
        WebDriverWait wait = new WebDriverWait(driver, 40);
        executor.executeScript("arguments[0].click();", loginButton);
    }

While executing the script that interacts with the page, calling the clickMainButton(); method works correctly. However, calling the clickLoginButton(); method results in a null pointer exception:

java.lang.NullPointerException
at pages.MainPage.clickLoginButton(MainPage.java:55)

If I create an instance of the Javascript Executor inside the clickLoginButton(); method, it functions properly. My question is how to implement the Javascript Executor correctly within the Page Object Model without needing to create a new instance in every method?

Answer №1

Resolved the issue with a solution:

To properly initialize the Javascript Executor within the class and constructor, follow this corrected approach:

public class MainPage {

WebDriver driver;
private WebDriverWait wait10;
private WebDriverWait wait40;
JavascriptExecutor executor;


@FindBy(xpath = "//*[@id='main_button']/div/span")
WebElement mainButton;

@FindBy(xpath = "//*[@id='login_button']/div/span")
WebElement loginButton;

// Constructor for initializing elements
public MainPage(WebDriver driver) {
    this.driver = driver;
    this.executor = (JavascriptExecutor) this.driver;
    this.wait10 = new WebDriverWait(driver, 10);
    this.wait40 = new WebDriverWait(driver, 40);
    PageFactory.initElements(driver, this);
}

// Method to click on mainButton using WebDriver
public void clickMainButton() {
    wait40.until(ExpectedConditions.elementToBeClickable(mainButton)).click();
}

// Method to click on loginButton using JS Executor
public void clickLoginButton() {
    executor.executeScript("arguments[0].click();", loginButton);
}

This same approach can be used for WebDriverWait with varying explicit wait times, as demonstrated in the constructor.

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

Automatically launch a popup window specified in JavaScript

Aim:- I am trying to automatically open a radwindow from the server-side based on a specific IF condition. Snippet Used:- In the aspx page, I have defined the radwindow as follows: <telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal= ...

I am having trouble getting my AngularJS client to properly consume the RESTful call

As I venture into the world of AngularJS and attempt to work with a RESTful service, I am encountering a challenge. Upon making a REST call to http://localhost:8080/application/webapi/myApp/, I receive the following JSON response: { "content": "Hel ...

Dealing with client cancellation requests in a Spring 3 application

In my Controller, I have a method that is mapped with @RequestMapping and returns an object in JSON format using @ResponseBody. This method includes a wait() on an object, creating a producer/consumer scenario. The client has the ability to cancel their r ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...

What is the best way to integrate external *.java files into my Android application?

Although it may seem like a simple question, I am struggling to find the answer and do not have the right words to search for it myself. Over the past two weeks, I have been working on my first Android app using Android Studio. Now, I want to implement a ...

Testing AJAX requests across different domains on a local server setting

While working in my local development environment at , I encountered the need to make an Ajax call to open a URL and display the response in fancybox. Due to the local development environment, this creates a cross-domain issue. However, once deployed to ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

Error: When attempting to access the 'name' property of an undefined object, a TypeError is thrown. However, accessing another property on the same object does

Retrieving information from API. The fetched data looks like [{"_id":"someId","data":{"name":"someName", ...}}, ...] My state and fetching process are as follows: class Table extends React.Component { constructor() { super(); this.state = { ...

What is the best way to properly store an axios request in the Vuex store in Vue.js?

I am exploring the idea of creating a dynamic sidebar with links fetched from an API. The theme I am currently working with can be found here: One interesting feature in this theme is the charts link, which displays a list of children in the sidebar. My ...

Being able to simultaneously open multiple pages in new tabs allows for

Is it possible to open a new tab using JavaScript and close the current page at the same time? Here is the code I have tried: <a href="#" onclick="window.open('test_2.php', '_blank'); window.close();">Click here</a> The n ...

What strategies can be implemented to avoid PHP timeouts when running loops, without adjusting the max_execution_time setting?

I am facing a challenge with a folder full of documents that need to be processed by a PHP script. There are around 1000 documents in the folder, and each one needs to be deleted after processing. Is there a way to efficiently run or restart a PHP script ...

The unique index in MongoDB seems to be failing to enforce uniqueness

I have implemented Mongodb in my Java application. The collection and index creation process is as follows: collection = mongoClient.getDB(DB_NAME).getCollection(COLLECTION_NAME) collection.ensureIndex(new BasicDBObject(['customerReference': 1, ...

Creating a modal form with jQuery in ASP.NET

I'm fairly new to ASP.NET development and have been able to work on simple tasks so far. However, I now have a more complex requirement that I'm struggling with. My goal is to create a modal form that pops up when a button is clicked in order to ...

Is it important to avoid two-way databinding in Angular 2 when it is not needed?

I have been conducting extensive research to determine if there would be any negative performance impact if I consistently use two-way data binding (ng-model) in all of my forms instead of one-way data binding. I am aware that with Angular 1, a new watch ...

Spring MVC is preventing the completion of the request due to CORS restrictions

Currently facing a CORS problem while trying to send requests from React.js to my spring MVC application. I have attempted to enable it in the ApplicationContext.xml file with no success. Added the following lines to the applicationcontext.xml file, but e ...

Parallel processing in selenium creates a separate window for every task

Currently, I am in the process of developing a web-bot that is designed to complete typing exercises on a specific website. To achieve this, I am utilizing Selenium along with undetected-chromedriver, which serves as an optimized version of the regular chr ...

What is the best way to eliminate excess elements from overflow:hidden?

Whenever I click on a modal, it changes my body to overflow:hidden. As a result, the scrollbar disappears and my page becomes unscrollable. Once I close the modal, my body reverts back to overflow:auto allowing the page to scroll again. These functionaliti ...

Using AngularJS to link ng-include in an ng-view HTML file

Currently, I am diving into AngularJs while also investigating the creation of a viral movie website for the new x-men film. The site in question is Trask Industries (http://www.trask-industries.com/#/innovation), where the navigation system seems to dynam ...

Is it possible to utilize AJAX requests in order to create a marker on google maps that updates in real-time?

My goal is to develop an app that generates a real-time updating google map, and I have been advised that AJAX requests can help achieve this. Nevertheless, after studying the documentation, I am uncertain about how to apply this method to solve my issue ...