Sam H
Sam H

Reputation: 561

Node.JS selenium send key enter

when i send a the reutn key in nodejs it gives a error?

driver.findElement(By.id('twofactorcode_entry')).sendKeys(Keys.ENTER);

All the sites tell me this is what i need to use? any help please

Upvotes: 5

Views: 29676

Answers (5)

ME-ON1
ME-ON1

Reputation: 83

You import Key from 'selenium-webdriver' but you are using

Keys.ENTER

but it should be

Key.ENTER

Upvotes: 0

Peter Grainger
Peter Grainger

Reputation: 5117

I'm assuming you are using npm package Selenium Webdriver: https://www.npmjs.com/package/selenium-webdriver

The error Keys is not defined occurs because you haven't defined keys before using it. You need to use the Enum Key (https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Key.html)

It is a constant on the driver module and exported as Key (note the singular form). I've put the updated code below.

const driver = require('selenium-webdriver')

driver.findElement(By.id('twofactorcode_entry')).sendKeys('webdriver', driver.Key.ENTER);

Extra tip: I've been using http://webdriver.io/ and it's a little easier to use than this library

Upvotes: 13

Elias Gezahegn
Elias Gezahegn

Reputation: 55

this worked for me

const {Builder, By, Key, until} = require('selenium-webdriver');
 
(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  try {
    await driver.get('http://www.google.com/ncr');
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
  } finally {
    await driver.quit();
  }
})();

Upvotes: 4

corolla
corolla

Reputation: 5656

For some reason the other solutions didn't work for me.

Using Node.js, it seems you can just use \n for enter:

await driver.findElement(By.id('my-field-id')).sendKeys('my-value\n');

Upvotes: 4

Gaz McGuffman
Gaz McGuffman

Reputation: 11

//Or alternatively define the Keys variable at the top..... e.g

var webdriver = require('selenium-webdriver'),
Keys = webdriver.Key,
By = webdriver.By,
until = webdriver.until;

Upvotes: 1

Related Questions