Executing Script Functions with Additional Parameters in Selenium: A Comprehensive Guide

Whenever I try to execute a script with functions that have multiple parameters, I keep getting an error:

Exception in thread "main" org.openqa.selenium.JavascriptException: ReferenceError: coords is not defined

This is my script:

enter code here

if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor) driver).executeScript("setNewCellType(new ZmianaTypuCommandFactory(),currentRozdzial,currentTable,this.activeCoords)");

I found the functions in the developer's tools and their format is:

 function setNewCellType(factory,nrRozdzial,tab,coords,newState,mode)

I set a breakpoint at this point to retrieve the parameters, and the parameters are:

setNewCellType(newZmianaTypuCommandFactory(),currentRozdzial,currentTable,this.activeCoords,params);

this.activeCoords have value 
(col: 2
colspan: 1
row: 2
rowspan: 1
siatkaCol: 2
siatkaRow: 2)

Can someone help me resolve this issue?

The element I am trying to use has a dynamic value, which changes during each session.

Additional scripts:

 driver.findElement(By.id("addTableRowCount")).clear();
 driver.findElement(By.id("addTableRowCount")).sendKeys("9");
 driver.findElement(By.id("addTableColCount")).clear();
 driver.findElement(By.id("addTableColCount")).sendKeys("2");
 driver.findElement(By.id("addTableOK")).click();
 driver.switchTo().defaultContent();
 driver.findElement(By.id("tytulTabeli")).sendKeys("Tytuł tabeli - 1");
 wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//p[text()='Obszar danych']")));
 driver.findElement(By.xpath("//p[text()='Obszar danych']")).click();   
    if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor) driver)
        .executeScript("setNewCellType(new ZmianaTypuCommandFactory(),currentRozdzial,currentTable,this.activeCoords)");

@Zhivko.Kostadinov

var ZmianaTypuCommandFactory = Class.create(CellTypeChangeCommandFactory,{
initialize:  function($super){
$super(new ZmianaTypuValidator());
this.wymagalnoscFactory = new WymagalnoscCommandFactory();
},
createSingleCmd:    function(nrRozdzial,tab,coords,newState){
if(newState.cellType.cellTypeInt == TYPY_KOMOREK.ZAZNACZENIE.cellTypeInt)
{ var cmd = new CompositeCommand();
var typeCmd = new ZmianaTypuCommand();
typeCmd.setState(tab,coords,newState);
cmd.addCommand(typeCmd);
var wymagalnoscCmd = this.wymagalnoscFactory.createCmd(nrRozdzial,tab,coords,true);
if(wymagalnoscCmd){
 cmd.addCommand(wymagalnoscCmd);
return cmd;
}
else{
return typeCmd;}}
else{
var cmd = new ZmianaTypuCommand();
cmd.setState(tab,coords,newState);
return cmd; }}});

Answer №1

It is highly likely that the issue lies within this segment:

this.activeCoords

Keep in mind that the "this" pointer is dependent on the context it is in. It is crucial to pass "absolute references", something that can be referenced from the console since the script executor typically runs in a global context.

A reliable validation method for test scripts is to check if you can execute them in the developer tools console, as they should also work with the scriptExecutor.

If the data remains constant throughout the test, you can utilize the following approach:

executeScript("setNewCellType(new ZmianaTypuCommandFactory(),currentRozdzial,currentTable,
{
    col: 2
    colspan: 1
    row: 2
    rowspan: 1
    siatkaCol: 2
    siatkaRow: 2 
},
{
   cellType: {type:'Kw'}
}
)");

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

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

ForEach function does not work following a shallow copy

I'm encountering an issue where forEach is not recognized as a function. Can someone assist me with this problem? Essentially, I need to generate a shallow copy of filteredSettlements and use it for looping through the items. Below is a snippet of the ...

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

Learn the process of converting Null values to empty strings within a chain of functions when manipulating a database

Currently, I am utilizing the lodash library and have the following code in place: data: _(responseData.data) .pick(['title', 'layout', 'slug', 'author', 'seo', 'css', 'js']) ...

Selenium objects disappear from view

My selenium test is currently running smoothly at a resolution of 1920 * 1080. However, I have been tasked with adapting this test to work on different common resolutions, such as 1366 * 768. The issue arises when running the Selenium test on smaller reso ...

What could be causing the unusual alignment of the 'pixels' on my resized HTML5 canvas?

Currently, I am in the process of creating a simple HTML5 canvas/JavaScript snake game inspired by the classic Nokia Snake. This is my first attempt at developing a game using HTML5 canvas and JavaScript, and I must admit, I am still a novice programmer! ...

After leaving the loop, the Element is no longer connected to the DOM. The Command duration or timeout is 21 milliseconds

I encountered the following issue with the code snippet provided below: Opens a page Check if the new month is available Downloads new month ex: Oct Then exits the loop and should download Sep However, upon exiting the loop, the above error message is t ...

Most efficient method for revealing all concealed divs using JavaScript

I have a large div containing multiple hidden divs that can be displayed individually or all at once. Here is an example of how it's structured: <div class="maindiv"> Print "<a href=javascript:show()>Click here to show all</a> ...

React does not support custom hooks as a function

Every time I attempt to invoke a function from my custom hook, an error message pops up on the screen upon loading stating that setAuth is not recognized as a function. useAuth.js import { useContext } from "react"; import AuthContext from " ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

JavaScript controller with numerous dependencies in AngularJS

I have created a new controller: .controller('myCtrl', function($scope, $route, $routeParams, $location) Now I am trying to inject something called SharedState. I attempted: .controller('chatCtrl' ['SharedState', function($ ...

What steps should I take to resolve a Selenium error in my Meteor application?

When running my code on the Meteor server (which operates on top of Node.js) from a method: var webdriver = require('selenium-webdriver') function getPage(page) { driver = driver || new webdriver.Builder().forBrowser('chrome&a ...

Is there a way to position two Grid elements to the left and one to the right in Material UI, especially if the first Grid element has a specified width

I'm currently using Material UI and have a Grid layout with three items. The left item needs to have a fixed width of 240px and be aligned to the left. The middle item should be left justified and can have any width, containing buttons that I've ...

Issue with Heroku not properly configuring cookies in a Node.js application

I have deployed my react app on xxx.herokuapp.com, and my node app on yyy.herokuapp.com. Both are functioning properly, and the backend is able to successfully send data to the front end. However, I am encountering an issue when trying to send a cookie. Th ...

Issue with importing a library into a Next.js component

I seem to be facing an unusual issue with my Nav component. Although I am able to import various items in my other components without any problems, for some reason, I cannot import anything into my Nav component. import { useState, useEffect } from "r ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

Display temperature in the format of '27.0 °C' using either query manipulation or Javascript code

A group of friends and I have embarked on a small IoT project, aiming to control certain aspects via a website accessible on mobile devices. Our main focus is a range slider that adjusts the temperature in a room, with an Arduino managing the actual tempe ...

JavaScript: Dynamic animation of a DIV element based on conditions

I am looking to create an animation for a DIV layer when another div is clicked. However, I only want the animation to play if the DIV layer has not been animated yet. My initial thought was to check the height value, as I am animating the height of the d ...

iOS displaying CSS Transform issue exclusively

Creating a website that is fully mobile responsive is my goal. However, after designing the header, I realized that it wasn't displaying correctly on IOS devices like my iPad. The "Transform: translateX(-100%);" statement was functional on Android pho ...

Navigate to a section that has been dynamically loaded through ajax

My page displays a list of products in alphabetical order, with the products dynamically loaded via ajax as the user scrolls. At the top of my page, I have an alphabet list (A-Z) that allows users to click on any letter to jump to the list of products st ...