Tips for holding down a non-modifier key, like the space key, with selenium as a user

I encountered an issue where selenium is unable to press and hold a key that is not included in the list of predefined keys:

Keys.SHIFT,
Keys.CONTROL,
Keys.ALT,
Keys.META,
Keys.COMMAND,
Keys.LEFT_ALT,
Keys.LEFT_CONTROL,
Keys.LEFT_SHIFT

In my application, instructions are displayed only when the space key is pressed and held down. I need to create browser tests for this scenario.

I am using ProtractorJS, but it seems like there is a general limitation in selenium for performing such actions. Whenever I try to use keyDown for a non-modifier key, an exception is thrown with a message stating: "Key Down / Up events only make sense for modifier keys."

Here is the link to the Selenium Java code: https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/interactions/internal/SingleKeyAction.java#L48

The same check can be found in Selenium JS code: https://github.com/SeleniumHQ/selenium/blob/master/javascript/webdriver/actionsequence.js#L301

Is there a way to press and hold a non-modifier key? Specifically, the space key in my case.

UPDATE: Thanks to the answer provided by Florent B., I was able to make it work after some modifications. I had to switch to a frame and dispatch the event to the document instead of a specific element for my use case.


browser.switchTo().frame('workspace');
const SIMULATE_KEY =
"var e = new Event('keydown');" +
"e.keyCode = 32;" + //spacebar keycode
"e.which = e.keyCode;" +
"e.altKey = false;" +
"e.ctrlKey = false;" +
"e.shiftKey = false;" +
"e.metaKey = false;" +
"e.bubbles = true;" +
"document.dispatchEvent(e);";
browser.executeScript(SIMULATE_KEY);

Answer №1

The Selenium API is lacking in providing this particular feature, as stated in the official documentation:

https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol

According to the server's requirements, each key pressed on the keyboard that does not need modifiers should be sent as a keydown event followed by a keyup event.

Nevertheless, there is a workaround to simulate key events using Javascript:

const SIMULATE_KEY =
  "var e = new Event(arguments[0]);" +
  "e.key = arguments[1];" +
  "e.keyCode = e.key.charCodeAt(0);" +
  "e.which = e.keyCode;" +
  "e.altKey = false;" +
  "e.ctrlKey = false;" +
  "e.shiftKey = false;" +
  "e.metaKey = false;" +
  "e.bubbles = true;" +
  "arguments[2].dispatchEvent(e);";

var target = driver.findElement(By.Id("..."));

// press the key "a"
browser.executeScript(SIMULATE_KEY, "keydown", "a", target);

// release the key "a"
browser.executeScript(SIMULATE_KEY, "keyup", "a", target);

Answer №2

If you're unable to locate a solution using selenium, you could consider utilizing a different tool (like AutoIt or AutoHotKey) in order to simulate the key press and hold action.

While it may be challenging, this alternative method might be your best bet.

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

Creating a hierarchical JSON object from user inputs: A step-by-step guide

I am looking to dynamically generate the following JSON Object from inputs: { "name": "USA", "parents": [ { "state": "California", "id": "12", "child": [ { "city": "Los Angeles", "id": "1" ...

Do not remove the attribute from JavaScript objects

Based on the EcmaScript specification, there are certain object properties that are supposed to be undeletable due to the internal parameter DontDelete. For example: var y = 5 should not be able to be deleted. However, upon further investigation, it seem ...

When inspecting a webpage, a specific tag can be visible, but when attempting to scrape data using Python, the tag cannot be located

Currently, Amazon is withholding prices from the category page for various categories when attempting to scrape data from a different country. Even on the product page, pricing remains hidden until the user clicks "See all buying options". The price is loc ...

I am interested in retrieving document information from Firebase

/* eslint-disable indent */ import React, { useEffect, useState } from 'react'; import { Alert, } from 'react-native'; import firebase from 'firebase'; // import { useIsFocused } from '@react-navigation/native'; im ...

Modify the CSS of a single element when a class is applied to a different element

I need to apply a specific CSS attribute to my submit button on the comments form when a user is logged in to Wordpress! When the .comment-form class contains p class="logged-in-as" instead of the standard p class="comment-notes", I want the p.form-submit ...

Get rid of the unnecessary vertical line that is located at the end of the string

I have come across a situation similar to the one demonstrated in this code snippet: http://plnkr.co/edit/eBjenGqgo3nbnmQ7XxF1?p=preview Currently, I am working with AngularJS 1.5.7. The directives used in my input - ( first ) textarea are the same as tho ...

Guide to incorporating code for Development and Staging environments in a cucumber framework

When testing at work, I encounter different data in the Dev and Staging environments. Additionally, I do not need to verify the database in the backend when testing Staging. How can I implement code with varying conditions in my framework? I attempted to ...

Add information if the data does not exist, modify it if it does

My current project involves creating a TS3 bot using the Node.js Library from Multivit4min on GitHub. The purpose of this bot is to perform the following tasks: nick (txt) cldbid (int) clid (txt) lastChannel (int) Event #1 - When a client connects to a ...

The reason behind my unsuccessful attempt to utilize AJAX with the Google GeoChart API

Learning about JavaScript is exciting! I recently tried incorporating a Google Geochart to generate visual reports. The sample code looked like this: function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

What could be the reason my CSS and Javascript animation is not functioning properly?

Currently working on creating a dynamic animation menu using CSS and Javascript, but encountering some issues. The concept involves having a menu with initially hidden opacity (using CSS), which becomes visible when the hamburger menu is clicked, sliding i ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Discord.js messageCollector filtering options

I am looking to set up a MessageCollector with multiple users in Discord. Here is what I have so far: const collector = new Discord.MessageCollector(channel, m => m.author.id === "123456789" || m.author.id === "978654321" , { max: 2000, maxMa ...

Tips for reloading a page when using the back button on MAC Safari

On my ASP.NET MVC application, I have two pages (A and B) with checkboxes and textboxes on page A. After moving from page B to page A using the browser back button in Safari on MAC, the page does not refresh and retains the old values for checkboxes and t ...

Skipping a row during the execution of a for loop when the row is empty can be achieved by implementing

Having two Excel sheets, I am using the testNg Assertion to compare cell values. In both sheet1 and sheet2, after david, there is an empty row causing my script to fail as it does not move from row 3 to row 4. Sheet1 Sheet2 sachin sachin david david ...

Acquire the worth of the <MenuItem> element from React's mui/material library

I am attempting to retrieve the value of the selected item listed below: Here is my attempt at logging this information: console.log("Event: ", event.currentTarget); Output: <li class="MuiButtonBase-root MuiMenuItem-root MuiMenuItem-gut ...

Is the unavailability of nodejs's require function in this closure when using the debugger console due to a potential v8 optimization?

I am facing an issue with using the require function in node-inspector. I copied some code from node-inspector and tried to use require in the debugger console to access a module for debugging purposes, but it is showing as not defined. Can someone help me ...

What is the best method for creating an Allure Report and viewing it without the need for a webserver or the use of browser

I am currently utilizing the Allure framework to create a report for my Selenium WebDriver tests. I am able to generate and access the report using allure generate allure open viewed through a web server However, the issue arises when our third-party aud ...

"Is it possible to selectively load only a few images on a website that contains numerous

My website displays numerous images hosted on a server. Each page contains a maximum of 100 images, each within its own div element. At any given moment, only one div is visible due to the CSS "display" property, while the others are hidden using display:n ...