General example
source
const {Builder, By, Key, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Enter text "cheese" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('cheese', Key.ENTER);
let firstResult = await driver.wait(until.elementLocated(By.css('h3')), 10000);
console.log(await firstResult.getAttribute('textContent'));
}
finally{
await driver.quit();
}
})();
Installing browser drivers
source
const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('chrome').build();
//your code inside this block
})();
chrome.setDefaultService(new chrome.ServiceBuilder('path/to/chromedriver').build());
const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('firefox').build();
//your code inside this block
})();
const firefox = require('selenium-webdriver/firefox');
const serviceBuilder = new firefox.ServiceBuilder("/path/to/geckodriver");
(async function myFunction() {
let driver = await new Builder()
.forBrowser('firefox')
.setFirefoxService(serviceBuilder)
.build();
//your code inside this block
})();
const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('MicrosoftEdge').build();
//your code inside this block
})();
const {Builder} = require("selenium-webdriver");
const edge = require('selenium-webdriver/edge');
let service = new edge.ServiceBuilder("/path/to/msedgedriver.exe");
(async function test() {
let driver = await new Builder()
.setEdgeService(service)
.forBrowser('MicrosoftEdge')
.build();
})();
const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('internet explorer').build();
//your code inside this block
})();
const {Builder} = require("selenium-webdriver");
const ie = require('selenium-webdriver/ie');
let service = new ie.ServiceBuilder("/path/to/IEDriverServer.exe");
(async function test() {
let driver = await new Builder()
.setIeService(service)
.forBrowser('internet explorer')
.build();
})();
const {Builder} = require("selenium-webdriver");
const opera = require('selenium-webdriver/opera');
(async function test() {
let driver = await new Builder()
.forBrowser('opera')
.build();
})();
const {Builder} = require('selenium-webdriver');
(async function myFunction() {
let driver = await new Builder().forBrowser('safari').build();
//your code inside this block
})();
Browser manipulation
source
await driver.get('https://selenium.dev');
await driver.getCurrentUrl();
await driver.navigate().back();
await driver.navigate().forward();
await driver.navigate().refresh();
await driver.getTitle();
await driver.getWindowHandle();
//Store the ID of the original window
const originalWindow = await driver.getWindowHandle();
//Check we don't have other windows open already
assert((await driver.getAllWindowHandles()).length === 1);
//Click the link which opens in a new window
await driver.findElement(By.linkText('new window')).click();
//Wait for the new window or tab
await driver.wait(
async () => (await driver.getAllWindowHandles()).length === 2,
10000
);
//Loop through until we find a new window handle
const windows = await driver.getAllWindowHandles();
windows.forEach(async handle => {
if (handle !== originalWindow) {
await driver.switchTo().window(handle);
}
});
//Wait for the new tab to finish loading content
await driver.wait(until.titleIs('Selenium documentation'), 10000);
// Opens a new tab and switches to new tab
await driver.switchTo().newWindow('tab');
// Opens a new window and switches to new window
await driver.switchTo().newWindow('window');
//Close the tab or window
await driver.close();
//Switch back to the old tab or window
await driver.switchTo().window(originalWindow);
await driver.quit();
/**
* Example using Mocha
* https://mochajs.org/#hooks
*/
after('Tear down', async function () {
await driver.quit();
});
try {
//WebDriver code here...
} finally {
await driver.quit();
}
// This won't work. Selenium is only aware of the elements in the top level document.
// To interact with the button, we will need to first switch to the frame.
await driver.findElement(By.css('button')).click();
// Store the web element
const iframe = driver.findElement(By.css('#modal > iframe'));
// Switch to the frame
await driver.switchTo().frame(iframe);
// Now we can click the button
await driver.findElement(By.css('button')).click();
// Using the ID
await driver.switchTo().frame('buttonframe');
// Or using the name instead
await driver.switchTo().frame('myframe');
// Now we can click the button
await driver.findElement(By.css('button')).click();
// Switches to the second frame
await driver.switchTo().frame(1);
// Return to the top level
await driver.switchTo().defaultContent();
// Access each dimension individually
const { width, height } = await driver.manage().window().getRect();
// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const width1 = rect.width;
const height1 = rect.height;
await driver.manage().window().setRect({ width: 1024, height: 768 });
// Access each dimension individually
const { x, y } = await driver.manage().window().getRect();
// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const x1 = rect.x;
const y1 = rect.y;
// Move the window to the top left of the primary monitor
await driver.manage().window().setRect({ x: 0, y: 0 });
await driver.manage().window().maximize();
await driver.manage().window().minimize();
await driver.manage().window().fullscreen();
let {Builder} = require('selenium-webdriver');
let fs = require('fs');
(async function example() {
let driver = await new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Returns base64 encoded string
let encodedString = await driver.takeScreenshot();
await fs.writeFileSync('./image.png', encodedString, 'base64');
await driver.quit();
}())
const {Builder, By} = require('selenium-webdriver');
let fs = require('fs');
(async function example() {
let driver = await new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
let ele = await driver.findElement(By.css("h1"));
// Captures the element screenshot
let encodedString = await ele.takeScreenshot(true);
await fs.writeFileSync('./image.png', encodedString, 'base64');
await driver.quit();
}())
// Stores the header element
let header = await driver.findElement(By.css('h1'));
// Executing JavaScript to capture innerText of header element
let text = await driver.executeScript('return arguments[0].innerText', header);
const {Builder} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
let opts = new chrome.Options();
let fs = require('fs');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(opts.headless())
.build();
await driver.get('https://www.selenium.dev');
try {
let base64 = await driver.printPage({pageRanges:["1-2"]});
await fs.writeFileSync('./test.pdf', base64, 'base64');
} catch (e) {
console.log(e)
}
await driver.quit();
})();
Locating elements
source
const cheese = driver.findElement(By.id('cheese'));
const cheese = driver.findElement(By.id('cheese'));
const cheddar = cheese.findElement(By.id('cheddar'));
const cheddar = driver.findElement(By.css('#cheese #cheddar'));
const muchoCheese = driver.findElements(By.css('#cheese li'));
let passwordField = driver.findElement(By.id('password'));
let emailAddressField = await driver.findElement(locateWith(By.tagName('input')).above(passwordField));
let emailAddressField = driver.findElement(By.id('email'));
let passwordField = await driver.findElement(locateWith(By.tagName('input')).below(emailAddressField));
let submitButton = driver.findElement(By.id('submit'));
let cancelButton = await driver.findElement(locateWith(By.tagName('button')).toLeftOf(submitButton));
let cancelButton = driver.findElement(By.id('cancel'));
let submitButton = await driver.findElement(locateWith(By.tagName('button')).toRightOf(cancelButton));
let emailAddressLabel = driver.findElement(By.id("lbl-email"));
let emailAddressField = await driver.findElement(locateWith(By.tagName("input")).near(emailAddressLabel));
Waits
source
await driver.get('file:///race_condition.html');
const element = driver.findElement(By.css('p'));
assert.strictEqual(await element.getText(), 'Hello from JavaScript!');
const documentInitialised = () =>
driver.executeScript('return initialised');
await driver.get('file:///race_condition.html');
await driver.wait(() => documentInitialised(), 10000);
const element = driver.findElement(By.css('p'));
assert.strictEqual(await element.getText(), 'Hello from JavaScript!');
let ele = await driver.wait(until.elementLocated(By.css('p')),10000);
let foo = await ele.getText();
assert(foo == "Hello from JavaScript");
await driver.wait(until.elementLocated(By.id('foo')), 30000);
(async function(){
// Apply timeout for 10 seconds
await driver.manage().setTimeouts( { implicit: 10000 } );
// Navigate to url
await driver.get('http://somedomain/url_that_delays_loading');
let webElement = driver.findElement(By.id("myDynamicElement"));
}());
const {Builder, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
await driver.get('http://somedomain/url_that_delays_loading');
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
let foo = await driver.wait(until.elementLocated(By.id('foo')), 30000, 'Timed out after 30 seconds', 5000);
})();
JS alerts, prompts, and confirmations
source
//Click the link to activate the alert
await driver.findElement(By.linkText('See an example alert')).click();
// Wait for the alert to be displayed
await driver.wait(until.alertIsPresent());
// Store the alert in a variable
let alert = await driver.switchTo().alert();
//Store the alert text in a variable
let alertText = await alert.getText();
//Press the OK button
await alert.accept();
// Note: To use await, the above code should be inside an async function
//Click the link to activate the alert
await driver.findElement(By.linkText('See a sample confirm')).click();
// Wait for the alert to be displayed
await driver.wait(until.alertIsPresent());
// Store the alert in a variable
let alert = await driver.switchTo().alert();
//Store the alert text in a variable
let alertText = await alert.getText();
//Press the Cancel button
await alert.dismiss();
// Note: To use await, the above code should be inside an async function
//Click the link to activate the alert
await driver.findElement(By.linkText('See a sample prompt')).click();
// Wait for the alert to be displayed
await driver.wait(until.alertIsPresent());
// Store the alert in a variable
let alert = await driver.switchTo().alert();
//Type your message
await alert.sendKeys("Selenium");
//Press the OK button
await alert.accept();
//Note: To use await, the above code should be inside an async function
HTTP proxies
source
let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let proxy = require('selenium-webdriver/proxy');
let opts = new chrome.Options();
(async function example() {
opts.setProxy(proxy.manual({http: '<HOST:PORT>'}));
let driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get("https://selenium.dev");
}
finally {
await driver.quit();
}
}());
Page loading strategy
source
const {Builder, Capabilities} = require('selenium-webdriver');
const caps = new Capabilities();
caps.setPageLoadStrategy("normal");
(async function example() {
let driver = await new Builder().
withCapabilities(caps).
forBrowser('chrome').
build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
}
finally {
await driver.quit();
}
})();
const {Builder, Capabilities} = require('selenium-webdriver');
const caps = new Capabilities();
caps.setPageLoadStrategy("eager");
(async function example() {
let driver = await new Builder().
withCapabilities(caps).
forBrowser('chrome').
build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
}
finally {
await driver.quit();
}
})();
const {Builder, Capabilities} = require('selenium-webdriver');
const caps = new Capabilities();
caps.setPageLoadStrategy("none");
(async function example() {
let driver = await new Builder().
withCapabilities(caps).
forBrowser('chrome').
build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
}
finally {
await driver.quit();
}
})();
Web Element
source
let {Builder, By} = require('selenium-webdriver');
driver = new Builder().forBrowser('firefox').build();
(async function test(){
//Navigate to url
await driver.get('http://www.google.com');
// Get search box element from webElement 'q' using Find Element
let searchBar = driver.findElement(By.name('q'));
//Perform action using WebElement
await searchBar.sendKeys('Webdriver');
})();
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.example.com');
// Get all the elements available with tag 'p'
let elements = await driver.findElements(By.css('p'));
for(let e of elements) {
console.log(await e.getText());
}
}
finally {
await driver.quit();
}
})();
let {Builder, By} = require('selenium-webdriver');
driver = new Builder().forBrowser('firefox').build();
(async function test(){
//Navigate to url
await driver.get('http://www.google.com');
//Get and store DOM element '<form>'
let searchForm = driver.findElement(By.name('f'));
//Get search box element from webElement 'form'
let searchBar = searchForm.findElement(By.name('q'));
//Perform action using WebElement
await searchBar.sendKeys('Webdriver');
})();
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Get element with tag name 'div'
let element = driver.findElement(By.css("div"));
// Get all the elements available with tag name 'p'
let elements = await element.findElements(By.css("p"));
for(let e of elements) {
console.log(await e.getText());
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.google.com');
await driver.findElement(By.css('[name="q"]')).sendKeys("webElement");
// Get attribute of current active element
let attr = await driver.switchTo().activeElement().getAttribute("title");
console.log(`${attr}`)
})();
// Navigate to url
await driver.get('https://www.google.com');
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("btnK")).isEnabled();
// Navigate to url
await driver.get('https://the-internet.herokuapp.com/checkboxes');
// Returns true if element ins checked else returns false
let res = await driver.findElement(By.css("input[type='checkbox']:last-of-type")).isSelected();
// Navigate to URL
await driver.get('https://www.example.com');
// Returns TagName of the element
let value = await driver.findElement(By.css('h1')).getTagName();
// Navigate to url
await driver.get('https://www.example.com');
// Returns height, width, x and y coordinates referenced element
let element = await driver.findElement(By.css("h1")).getRect();
// Navigate to Url
await driver.get('https://www.example.com');
// Retrieves the computed style property 'color' of linktext
let cssValue = await driver.findElement(By.linkText("More information...")).getCssValue('color');
// Navigate to URL
await driver.get('http://www.example.com');
// retrieves the text of the element
let text = await driver.findElement(By.css('h1')).getText();
Keyboard
source
const {Builder, By, Key} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Enter text "webdriver" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('webdriver', Key.ENTER);
}
finally {
await driver.quit();
}
})();
const {Builder, By, Key} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Enter text "webdriver" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('webdriver', Key.ENTER);
// Perform action ctrl + A (modifier CONTROL + Alphabet A) to select the page
await driver.actions().keyDown(Key.CONTROL).sendKeys('a').perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By, Key} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store google search box WebElement
let search = driver.findElement(By.name('q'));
// Enters text "qwerty" with keyDown SHIFT key and after keyUp SHIFT key (QWERTYqwerty)
await driver.actions().click(search).keyDown(Key.SHIFT).sendKeys("qwerty").keyUp(Key.SHIFT).sendKeys("qwerty").perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'SearchInput' element
let searchInput = driver.findElement(By.name('q'));
await searchInput.sendKeys("selenium");
// Clears the entered text
await searchInput.clear();
}
finally {
await driver.quit();
}
})();
Remote Webdriver
source
const { Builder, Capabilities } = require("selenium-webdriver");
var capabilities = Capabilities.firefox();
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://example.com")
.withCapabilities(capabilities)
.build();
try {
await driver.get('http://www.google.com');
} finally {
await driver.quit();
}
})();
const { Builder } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
let opts = new chrome.Options();
opts.setAcceptInsecureCerts(true);
opts.setBrowserVersion('67');
opts.setPlatform('Windows XP');
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://example.com")
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get('http://www.google.com');
}
finally {
await driver.quit();
}
})();
var remote = require('selenium-webdriver/remote');
driver.setFileDetector(new remote.FileDetector);
driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload");
var upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
BiDi APIs
source
const {Builder} = require('selenium-webdriver');
(async function example() {
try {
let driver = await new Builder()
.forBrowser('chrome')
.build();
const pageCdpConnection = await driver.createCDPConnection('page');
await driver.register('username', 'password', pageCdpConnection);
await driver.get('https://the-internet.herokuapp.com/basic_auth');
await driver.quit();
}catch (e){
console.log(e)
}
}())
const {Builder, until} = require('selenium-webdriver');
const assert = require("assert");
(async function example() {
try {
let driver = await new Builder()
.forBrowser('chrome')
.build();
const cdpConnection = await driver.createCDPConnection('page');
await driver.logMutationEvents(cdpConnection, event => {
assert.deepStrictEqual(event['attribute_name'], 'style');
assert.deepStrictEqual(event['current_value'], "");
assert.deepStrictEqual(event['old_value'], "display:none;");
});
await driver.get('dynamic.html');
await driver.findElement({id: 'reveal'}).click();
let revealed = driver.findElement({id: 'revealed'});
await driver.wait(until.elementIsVisible(revealed), 5000);
await driver.quit();
}catch (e){
console.log(e)
}
}())
const {Builder} = require('selenium-webdriver');
(async () => {
try {
let driver = new Builder()
.forBrowser('chrome')
.build();
const cdpConnection = await driver.createCDPConnection('page');
await driver.onLogEvent(cdpConnection, function (event) {
console.log(event['args'][0]['value']);
});
await driver.executeScript('console.log("here")');
await driver.quit();
}catch (e){
console.log(e);
}
})()
const {Builder, By} = require('selenium-webdriver');
(async () => {
try {
let driver = new Builder()
.forBrowser('chrome')
.build();
const cdpConnection = await driver.createCDPConnection('page')
await driver.onLogException(cdpConnection, function (event) {
console.log(event['exceptionDetails']);
})
await driver.get('https://the-internet.herokuapp.com');
const link = await driver.findElement(By.linkText('Checkboxes'));
await driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", link, "onclick","throw new Error('Hello, world!')");
await link.click();
await driver.quit();
}catch (e){
console.log(e);
}
})()
await driver.get("https://www.duckduckgo.com");
await driver.sendAndGetDevToolsCommand('Performance.enable')
let result = await driver.sendAndGetDevToolsCommand('Performance.getMetrics')
console.log(result)
await driver.quit();
const connection = await driver.createCDPConnection()
let url = fileServer.whereIs("/cheese")
let httpResponse = new HttpResponse(url)
httpResponse.addHeaders("Content-Type", "UTF-8")
httpResponse.body = "sausages"
await driver.onIntercept(connection, httpResponse, async function () {
let body = await driver.getPageSource()
assert.strictEqual(body.includes("sausages"), true, `Body contains: ${body}`)
})
driver.get(url)
Driver specific capabilities
source
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
options.headless();
const driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
let profile = '/path to custom profile';
options.setProfile(profile);
const driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
.setIeOptions(options)
.build();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ensureCleanSession(true);
let driver = await Builder()
.setIeOptions(options)
.build();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ignoreZoomSetting(true);
let driver = await Builder()
.setIeOptions(options)
.build();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().introduceFlakinessByIgnoringProtectedModeSettings(true);
let driver = await Builder()
.setIeOptions(options)
.build();
const {Builder,By, Capabilities} = require('selenium-webdriver');
let caps = Capabilities.ie();
caps.set('silent', true);
(async function example() {
let driver = await new Builder()
.forBrowser('internet explorer')
.withCapabilities(caps)
.build();
try {
await driver.get('http://www.google.com/ncr');
}
finally {
await driver.quit();
}
})();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.addBrowserCommandSwitches('-k');
options.addBrowserCommandSwitches('-private');
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
On test automation
source
// Create a user who has read-only permissions--they can configure a unicorn,
// but they do not have payment information set up, nor do they have
// administrative privileges. At the time the user is created, its email
// address and password are randomly generated--you don't even need to
// know them.
var user = userFactory.createCommonUser(); //This method is defined elsewhere.
// Log in as this user.
// Logging in on this site takes you to your personal "My Account" page, so the
// AccountPage object is returned by the loginAs method, allowing you to then
// perform actions from the AccountPage.
var accountPage = loginAs(user.email, user.password);
// The Unicorn is a top-level Object--it has attributes, which are set here.
// This only stores the values; it does not fill out any web forms or interact
// with the browser in any way.
var sparkles = new Unicorn("Sparkles", UnicornColors.PURPLE, UnicornAccessories.SUNGLASSES, UnicornAdornments.STAR_TATTOOS);
// Since we are already "on" the account page, we have to use it to get to the
// actual place where you configure unicorns. Calling the "Add Unicorn" method
// takes us there.
var addUnicornPage = accountPage.addUnicorn();
// Now that we're on the AddUnicornPage, we will pass the "sparkles" object to
// its createUnicorn() method. This method will take Sparkles' attributes,
// fill out the form, and click submit.
var unicornConfirmationPage = addUnicornPage.createUnicorn(sparkles);
// The exists() method from UnicornConfirmationPage will take the Sparkles
// object--a specification of the attributes you want to see, and compare
// them with the fields on the page.
assert(unicornConfirmationPage.exists(sparkles), "Sparkles should have been created, with all attributes intact");
Mouse and keyboard actions in detail
source
const {Builder, By} = require('selenium-webdriver');
(async function clickAndHold() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'google search' button web element
let searchBtn = driver.findElement(By.linkText("Sign in"));
const actions = driver.actions({async: true});
// Perform mouseMove to element and mouseDown (press) action on the element
await actions.move({origin:searchBtn}).press().perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function contextClick() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'google search' button web element
let searchBtn = driver.findElement(By.linkText("Sign in"));
const actions = driver.actions({async: true});
// Perform context-click action on the element
await actions.contextClick(searchBtn).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function doubleClick() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'google search' button web element
let searchBtn = driver.findElement(By.linkText("Sign in"));
const actions = driver.actions({async: true});
// Perform double-click action on the element
await actions.doubleClick(searchBtn).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function moveToElement() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'Gmail' anchor web element
let gmailLink = driver.findElement(By.linkText("Gmail"));
const actions = driver.actions({async: true});
// Performs mouse move action onto the element
await actions.move({origin:gmailLink}).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function moveByOffset() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'Gmail' anchor web element
let gmailLink = driver.findElement(By.linkText("Gmail"));
// Capture offset positions of element
let offset = await gmailLink.getRect();
let x = await offset.x;
let y = await offset.y;
const actions = driver.actions({async: true});
// Performs mouse move action onto the element
await actions.move({x:parseInt(x),y:parseInt(y)}).pause(3000).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function dragAndDrop() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://crossbrowsertesting.github.io/drag-and-drop');
// Store 'box A' as source element
let sourceEle = driver.findElement(By.id("draggable"));
// Store 'box B' as source element
let targetEle = driver.findElement(By.id("droppable"));
const actions = driver.actions({async: true});
// Performs drag and drop action of sourceEle onto the targetEle
await actions.dragAndDrop(sourceEle, targetEle).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function dragAndDropBy() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://crossbrowsertesting.github.io/drag-and-drop');
// Store 'box A' as source element
let sourceEle = driver.findElement(By.id("draggable"));
// Store 'box B' as source element
let targetEle = driver.findElement(By.id("droppable"));
let offset = await targetEle.getRect();
let x = await offset.x;
let y = await offset.y;
const actions = driver.actions({async: true});
// Performs dragAndDropBy onto the target element offset position
await actions.dragAndDrop(sourceEle, {x:parseInt(x), y:parseInt(y)}).perform();
}
finally {
await driver.quit();
}
})();
const {Builder, By} = require('selenium-webdriver');
(async function release() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://crossbrowsertesting.github.io/drag-and-drop');
// Store 'box A' as source element
let sourceEle = driver.findElement(By.id("draggable"));
// Store 'box B' as source element
let targetEle = driver.findElement(By.id("droppable"));
const actions = driver.actions({async: true});
await actions.move({origin:sourceEle}).press().perform();
// Performs release event on target element
await actions.move({origin:targetEle}).release().perform();
}
finally {
await driver.quit();
}
})();
Working with cookies
source
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// set a cookie on the current domain
await driver.manage().addCookie({name:'key', value: 'value'});
})();
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// set a cookie on the current domain
await driver.manage().addCookie({name:'foo', value: 'bar'});
// Get cookie details with named cookie 'foo'
driver.manage().getCookie('foo').then(function (cookie) {
console.log('cookie details => ', cookie);
});
})();
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Add few cookies
await driver.manage().addCookie({name:'test1', value:'cookie1'});
await driver.manage().addCookie({name:'test2', value:'cookie2'});
// Get all Available cookies
driver.manage().getCookies().then(function (cookies) {
console.log('cookie details => ', cookies);
});
})();
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Add few cookies
await driver.manage().addCookie({name:'test1', value:'cookie1'});
await driver.manage().addCookie({name:'test2', value:'cookie2'});
// Delete a cookie with name 'test1'
await driver.manage().deleteCookie('test1');
// Get all Available cookies
driver.manage().getCookies().then(function (cookies) {
console.log('cookie details => ', cookies);
});
})();
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Add few cookies
await driver.manage().addCookie({name:'test1', value:'cookie1'});
await driver.manage().addCookie({name:'test2', value:'cookie2'});
// Delete all cookies
await driver.manage().deleteAllCookies();
})();
const {Builder} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
await driver.manage().addCookie({name:'key', value: 'value', sameSite:'Strict'});
await driver.manage().addCookie({name:'key', value: 'value', sameSite:'Lax'});
console.log(await driver.manage().getCookie('key'));
})();
source
const { Builder } = require("selenium-webdriver");
(async function geoLocationTest() {
const driver = await new Builder().forBrowser("chrome").build();
try {
await driver.get("https://my-location.org/");
const pageCdpConnection = await driver.createCDPConnection('page');
//Latitude and longitude of Tokyo, Japan
const coordinates = {
latitude: 35.689487,
longitude: 139.691706,
accuracy: 100,
};
await pageCdpConnection.execute(
"Emulation.setGeolocationOverride",
1,
coordinates
);
} catch (e) {
console.log(e)
} finally {
await driver.quit();
}
})();
const webdriver = require('selenium-webdriver');
const BROWSER_NAME = webdriver.Browser.CHROME;
async function getDriver() {
return new webdriver.Builder()
.usingServer('<grid-url>')
.forBrowser(BROWSER_NAME)
.build();
}
async function executeCDPCommands () {
let driver = await getDriver();
await driver.get("<your site url>");
const cdpConnection = await driver.createCDPConnection('page');
//Latitude and longitude of Tokyo, Japan
const coordinates = {
latitude: 35.689487,
longitude: 139.691706,
accuracy: 100,
};
await cdpConnection.execute(
"Emulation.setGeolocationOverride",
1,
coordinates
);
await driver.quit();
}
executeCDPCommands();
const {Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
// enable debugger for CDP
options.enableDebugger();
(async function example() {
try {
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(options).build();
const pageCdpConnection = await driver.createCDPConnection('page');
const metrics = {
width: 300,
height: 200,
deviceScaleFactor: 50,
mobile: true,
};
await pageCdpConnection.execute(
"Emulation.setDeviceMetricsOverride",
1,
metrics
);
await driver.get("https://www.google.com");
await driver.quit();
} catch (e) {
console.log(e);
}
})();