When retrieving computed styles using browser.executeScript, Protractor successfully returns values as strings but encounters issues when trying to access them as functions

I need to confirm the visibility of a tooltip popup by using the

window.getComputedStyle().visibility
property with Protractor framework.

When I provide a string to the executeScript function, everything works correctly. It returns visible:

// elementToCheck is an ElementFinder
async getComputedStyleVisibility(elementToCheck) {
    return await browser
         .executeScript(`return window.getComputedStyle(document.querySelector('${elementToCheck.locator().value}')).visibility`);
}

However, the issue arises when I try replacing the string in the executeScript with a function. It now returns hidden and seems to get stuck until the tooltip popup disappears.

It appears there may be a synchronization problem, but I'm having trouble pinpointing the exact cause:

// elementToCheck is an ElementFinder
async getComputedStyleVisibility(elementToCheck) {
    return await browser.executeScript(
        webElem => (window.getComputedStyle(webElem).visibility),
        await elementToCheck.getWebElement()
    );
}

Answer №1

To ensure your script functions as intended, it is crucial to correctly access the webElement.

According to the documentation,

Any additional arguments included with the script will be treated as script arguments and can be referenced using the arguments object

Thus, incorporating the arguments object in your script is essential. Here is an example:

async getComputedStyleVisibility(elementToCheck) {
    return await browser.executeScript(
        () => (window.getComputedStyle(arguments[0]).visibility),
        await elementToCheck.getWebElement()
    );
}

HOWEVER

If you are not constrained to solely use browser.executeScript(), it may be beneficial to reconsider your approach.

Protractor offers an API for verifying the presence of a specific element or similar scenarios.

Confirming the presence and visibility of an element for the user:

element(by.css("#a")).isDisplayed()
    .then(isDisplayed => console.log("element displayed?", isDisplayed))
    .catch(err => console.error("An error occurred. Element not present.", err))

In my opinion, resort to using browser.executeScript() only as a last option. Most common functionalities like clicking, checking presence, etc., are already efficiently handled by Protractor.

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

The mssql node is experiencing an issue where it is unable to accept work due to the pool being

Recently, I encountered an issue with my node js app that utilizes the npm mssql module. Despite purchasing a cloud Windows 2012 server, I faced an error when trying to execute a stored procedure. The error is thrown at ps.prepare("exec usp_Get_Cars @para ...

All API endpoints must be accessed with a jwt token

After diving into the nextjs documentation, I stumbled upon something interesting. import { getToken } from "next-auth/jwt" const secret = process.env.NEXTAUTH_SECRET export default async function handler(req, res) { // if using `NEXTAUTH_SEC ...

Manipulating arrays with multiple conditions using Vue.js and JavaScript

In my Vue.js application, I have implemented a navigation drawer to display the different pages accessible to users. The visibility of each page is determined by the activation status of the related module, indicated by a unique moduleID assigned to each p ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

I'm having trouble identifying the cause of the issue with the line breaking

I recently encountered an issue with a script while using the typed.js library. The code is supposed to output 3 lines followed by 1 final line, but it currently only outputs 2 lines and 1 final line. I attempted to fix the code, but it seems to freeze wit ...

The ThreeJS WebGLRenderTarget is displaying an empty texture

Utilizing A-Frame and Three.JS, my goal is to render to a WebGLRenderTarget and generate a material based on its texture. Here's a snippet of the code: var targetPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry(2, 2), new THREE.MeshBasicMate ...

JavaScript form button press tracker

Hello! I've been tackling a challenge involving a JavaScript function to count button clicks. The catch is, the button type is set to submit, causing the page to reload every time I click it. Below is the snippet of code that contains the problemati ...

Finding the attribute value within a nested array of objects retrieved from an API response

Imagine a scenario where I possess an array of unclassified objects, each of which contains an array of labeled objects: [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', e ...

Encountering an "AJAX not a function" error while using the d3/flask interface

Hey there! I'm new to the world of JavaScript and AJAX. Take a look at this d3 function I've been working on: var node = g.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ...

Struggling to align the h1 tag with a p tag on the same line

How can I align the balance to the upper right-hand corner of my website? I'm new to HTML and CSS and struggling to get the p tag next to the h1 tag. I've tried using display inline for the h1 tag and float right for the p tag, as well as setting ...

Incorporating CSS style to individual rows in an HTML table

Is there a way to determine if a specific string, such as 'LA DEFENSE', is present in my HTML table and then change the background color of that line to red? https://i.sstatic.net/Yq7qF.png This is what I am looking for: $("#colorline").click( ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Calculate the total sum by adding the values of the radio buttons that have been selected and then display or

Seeking help to troubleshoot my code! I want to calculate the sum of selected radio button values and display it at the end. Can anyone assist me with this issue? Thanks in advance! <html> <head> </head> <script type="text/javas ...

Modifying JavaScript prototypes on the fly can lead to troublesome issues

My curiosity has been piqued by the concept of dynamically changing a constructor's prototype in JavaScript, leading me to the findings above. It appears that an already constructed instance does not inherit the properties of the newly changed protot ...

What is the best way to trigger the second function on a click event?

Is there a way to trigger my 20 second timer with the click of a button, followed by an alert after the timer ends? HTML <aside class="start-box"> <button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startCloc ...

Issue with ng-click directive not triggering within an Ionic tag unless using interpolation

When attempting to pass a value to a function on ng-click, I noticed that it works outside of the ionic tag without interpolation. However, I am confused as to why I need to interpolate it within the ionic tag. Here is a sample of the code: <span ng-cl ...

Three.js - Model is unable to cast shadows

Greetings! I am currently diving into the world of three.js and utilizing react-three-fiber to integrate it with React. However, I've encountered a challenge regarding shadow casting between models. Despite setting obj.castShadow = true and obj.receiv ...

Angular: Utilizing the extend method in the child controller's scope

I am facing a challenge regarding the extension of methods in an angular child controller which is causing me some frustration. My main objective is to inherit all the public /$scope/ variables and methods from the parent controller into the child controll ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...

Revising the passport local strategy with promisification. Trouble arises with the implementation of .catch()

Implementing hash password functionality in an express + passport + local strategy app using bcrypt has been successful: var bcrypt = require('bcrypt-nodejs'); familySchema.pre('save', function(next) { var family = this; var SALT_ ...