Executing a function from a JavaScript file within Robot Framework

It is possible to run javascript from a file.

Run JavaScript    ${CURDIR}/js_to_run.js

However, I am wondering how to call a function by its name from this file?

Answer №1

Utilizing the Execute Javascript function as it comes may not allow for direct invocation of a specific function. However, it is feasible to pass the name of a function as an argument.

Execute Javascript    ${CURDIR}/js/utils.js    ARGUMENTS    clickElement    ${locator}

The script within the utils.js file:

var utils = utils || {};

(function (arguments) {
    utils.clickElement = function (locator) {
        // Function implementation
    }

    // Extracting and executing function based on passed arguments
    var functionName = [].shift.call(arguments);     
    utils[functionName].apply(this, arguments);
})(arguments);

Answer №2

Although it may not be the most elegant solution, sometimes you have to get creative in order to make things work. To inject your entire Javascript code and then call the function you injected, you can use the following method.

On the Google homepage, you can inject Javascript with the following code:

var s = document.createElement('script');
s.text = "document.getElementById('hplogo').addEventListener('click',function(){alert('Google');});";
document.getElementsByTagName('head')[0].appendChild(s);

In robotframework, you can achieve the same result using Execute Javascript:

Open Browser    https://www.google.com
Wait Until Page Contains Element    id=hplogo
Execute Javascript    var s = document.createElement('script');s.text = "document.body.addEventListener('click',function(){alert('Google')})";document.getElementsByTagName('head')[0].appendChild(s);
Sleep    2s          #wait so that injected javascript gets evaluated 
Execute Javascript    document.getElementById('hplogo').click();
Sleep    10s    #wait and click anywhere on body of the page to see the alert

Your s.text variable will contain the entire Javascript code from a JS file in a single line. While this may seem like messy work, sometimes it's necessary - as I experienced when implementing pdf export functionality on a website.

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

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

Dynamic parameters can be passed in Rails using the link_to method

Feeling a bit stuck, maybe this is just a simple question. I have a sort button that I need to use to organize my list of questions. To do this, I create a link_to like this: <%= link_to xx_path(:is_sort => true, :remote=> true , :method=> :p ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

JSON Nesting with Ember.js and Rails

I'm currently developing a simple Ember / Rails application that involves multiple nested relationships. For instance: class Release < ActiveRecord::Base has_many :tracks end Upon accessing my Releases endpoint, I receive JSON data in the follo ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Verify the quantity of opened links

Let's say I have 100 links. After some of them are clicked (as indicated by a change in color), how can I use Selenium to identify which links were opened? Any thoughts on this? Regards, JB. ...

Ensure that the objection model aligns with the TypeScript interface requirements

I am currently working on implementing an API using express, objection.js, and TypeScript. I found a lot of inspiration from this repository: https://github.com/HappyZombies/brackette-alpha/tree/master/server/src Similar to the creator, I aim to have var ...

Can jQuery be used to edit an XML file?

Can XML files be updated using jQuery, or is server-side scripting necessary for this task? Thank you ...

Getting the text from an HTML input field requires accessing the value property of the

My goal is to generate a pdf report using php. The user will enter their name in an input box, which will then be passed to the second php page that searches the mysql database. Issue: When the user inputs their name, attempting to retrieve the data (var ...

Guide to filtering out cookies using express-winston

After reviewing the README for express-winston, it appears that removing the headers from the logged line is quite straightforward: we can easily do so by adjusting the requestWhitelist option. However, this will disable logging all headers. Is there a wa ...

When importing a component that is passed as a prop in React, it is causing a blank page to render and is displaying an error in the

Visit this link for the code Everything was running smoothly with the app until I decided to include the Icon component in SidebarOption.js. Now, upon doing so, a blank page appears and an error is displayed in the console: An error occurred stating that ...

What is the best way to organize two separate arrays based on a single shared variable?

I have two separate arrays containing information. One array includes the title of each national park and other related data, while the second array consists of alerts from the entire NPS system. The common factor between these arrays is the parkCode. How ...

What are the best methods for implementing runtime type checking in JavaScript?

Utilizing either TypeScript or Facebook's Flow (type), I am empowered to statically assign types to variables like this: function add (x: integer, y: integer) { ... } Both TypeScript and Flow are able to identify and prevent incorrect invocations su ...

I aim to extract the orderID from the API response using Selenium with Python

My goal is to extract the unique order ID from the API response. Upon clicking the Create Order button, a POST API request is sent and the desired unique ID is returned. Here is the code snippet for creating an order: from datetime import date import time ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...