How run two Chrome driver for one profile with Selenium Webdriver Nodejs? - node.js

I write tests, and for the speed, i want, that user has already been authenticated (+ loaded data in local store).
import * as webdriver from 'selenium-webdriver';
import * as Chrome from 'selenium-webdriver/chrome';
var options = new Chrome.Options();
options.addArguments('--user-data-dir=C:\\profilepath');
var driver = new webdriver.Builder().withCapabilities(options.toCapabilities()).build();
driver.get("http://site.ru/").then(() => {
console.log('Opened');
}, (err) => {
console.log('Err', err);
});
var driver2 = new webdriver.Builder().withCapabilities(options.toCapabilities()).build();
driver2.get("http://site.ru/").then(() => {
console.log('Opened');
}, (err) => {
console.log('Error', err);
});
The first driver works good, opens the page, the second just hanging initial screen without any errors. Same for starts them in different processes ...

You have two entities working at cross-purpose here: Chrome and Selenium.
If you run Chrome from the command line and start it twice with the same profile, the second time you start it, Chrome is going to detect that there is already a Chrome instance running with the profile you selected and will instruct this Chrome instance to open a new window. I don't know what you'd see on the console on Windows but on Linux, the second time you try to start Chrome, you get this on the console:
Created new window in existing browser session.
So although it looks like you have a different Chrome instance, in fact you just have one instance with two windows. I do not believe it is possible to force Chrome to spawn a second instance with the same profile.
Then you have Selenium. When you use Builder to create a new Selenium instance, Selenium executes Chrome but as you already know from what I explained above, the 2nd time you do it, Chrome just opens a new window in the first Chrome instance you started. Selenium does not detect this but tries to connect to the browser to control it. However, Selenium already connected to the browser when you asked it to spawn the first Chrome instance, and it cannot connect again to the same instance. If you wait long enough, a timeout will occur and Selenium will report:
Error { [UnknownError: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.13.307649 (bf55b442bb6b5c923249dd7870d6a107678bfbb6),platform=Linux 4.0.0-2-amd64 x86_64)]
code: 13,
state: 'unknown error',
message: 'unknown error: Chrome failed to start: exited abnormally\n (Driver info: chromedriver=2.13.307649 (bf55b442bb6b5c923249dd7870d6a107678bf
6_64)',
name: 'UnknownError',
[...]
If your profile contains the credentials you need before you start your Selenium script, what you could do is just copy the profile to a new location for your second Chrome instance. It could look like this:
import * as webdriver from 'selenium-webdriver';
import * as Chrome from 'selenium-webdriver/chrome';
import * as fs_extra from 'fs-extra';
// Copy the profile to a new location for the new instance.
fs_extra.copySync("/tmp/t6/foo", "/tmp/t6/foo2");
var options = new Chrome.Options();
options.addArguments('--user-data-dir=/tmp/t6/foo');
var driver = new webdriver.Builder().withCapabilities(options.toCapabilities()).build();
driver.get("http://google.com/").then(() => {
console.log('Opened');
}, (err) => {
console.log('Err', err);
});
var options2 = new Chrome.Options();
options2.addArguments('--user-data-dir=/tmp/t6/foo2');
var driver2 = new webdriver.Builder().withCapabilities(options2.toCapabilities()).build();
driver2.get("http://example.com/").then(() => {
console.log('Opened');
}, (err) => {
console.log('Error', err);
});

Related

Failed to create session. unknown error: Chrome failed to start: was killed. (unknown error: DevToolsActivePort file doesn't exist)

I'm executing an automated test with Electron by using Selenium by using the following code:
const webdriver = require('selenium-webdriver');
var Application = require('spectron').Application;
var assert = require('assert');
const driver = new webdriver.Builder()
// The "9515" is the port opened by chrome driver.
.usingServer('http://localhost:9515')
.withCapabilities({
'goog:chromeOptions': {
// Here is the path to your Electron binary.
binary: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
},
})
.forBrowser('electron') // note: use .forBrowser('electron') for selenium-webdriver <= 3.6.0
.build();
describe('Application launch', function () {
var app;
jest.setTimeout(30000);
beforeEach(function () {
app = new Application({
path: 'node_modules/.bin/electron',
args: ['--headless', '--no-sandbox', '--disable-dev-shm-usage'],
});
return app.start();
});
afterEach(function () {
if (app && app.isRunning()) {
return app.stop();
}
});
it('click a button', function* () {
yield driver.sleep(5000);
});
});
But I'm obtaining the following error:
yarn run v1.22.19
warning package.json: License should be a valid SPDX license expression
warning ..\..\..\package.json: No license field
$ jest --NODE_ENV=test
FAIL src/__test__/App.spec.jsx (10.623 s)
Application launch
× click a button (6564 ms)
● Application launch › click a button
Failed to create session.
unknown error: Chrome failed to start: was killed.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location C:\Users\vipul\appname\src\node_modules\spectron\lib\launcher.bat is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
at startWebDriverSession (src/node_modules/webdriver/build/utils.js:72:15)
at Function.newSession (src/node_modules/webdriver/build/index.js:58:45)
at Object.remote (src/node_modules/webdriverio/build/index.js:73:22)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 11.878 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I've tried to add even the args suggested by several answers in other stackoverflow questions like --headless or --no-sandbox but even those not worked.
Try this file
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--no-sandbox");
options.add_argument("--headless")
options.add_argument("--disable-setuid-sandbox")
options.add_argument("--remote-debugging-port=9222") # this
options.add_argument("--disable-extensions")
#options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("enable-automation")
options.add_argument("--disable-infos")
options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.google.com/")
element_text = driver.page_source
print(element_text)

Selenium RemoteWebDriver() ERR_BLOCKED_BY_CLIENT on Chrome Extension in Selenium Grid, while without ChromeExtension works fine

We are using an extension in chrome for wiremock.
This chrome extension works beautifully while running locally both on Windows ( ref. 1), Mac computers.
However when instantiating RemoteWebDriver() in a Selenium Test Grid flavor named Moon, loading the extension fails (on Linux) catastrophically with ERR_BLOCKED_BY_CLIENT when trying to load the chrome extension.
(ref. 1)
On Windows localhost , execution actually fails with a message "That unpacked extensions is disabled by the admin"" but this can be easily workarounded by manually deleting a key at :
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallBlacklist
https://support.leapwork.com/hc/en-us/articles/360003031952-How-to-resolve-Error-Loading-of-unpacked-extensions-is-disabled-by-the-administrator
**- So I guess one needs to do something similar in the Test Grid node running Linux, but how does that code look like exactly? **
We have a switch statement in the code, so we see that code works generally fine in the test grid when tests are instantiated without the chrome extension.
Junit4.x
com.github.tomakehurst wiremock-jre8 2.32.0
jdk8 (we have so many indirect dependencies on about 77 or so different artifact versions so updating is almost impossible. (I suspect I will get the Nobel price in physics before that happens)
Chrome version 91.0.4472 is instantiated in the grid.
Error message :
idgpnmonknjnojddfkpgkljpfnnfcklj is blocked. This page has been blocked by Chrome. ERR_BLOCKED_BY_CLIENT”
We have tried a few different code constructs which all failed to unblock the extension from loading.
Here is one such code example we unsuccessfully tried with:
private RemoteWebDriver createDriver( Scenario scenario) {
RemoteWebDriver driver = null;
ChromeOptions options = mock ?
new ChromeOptions()
.addExtensions(new File("src/test/resources/modheader/idgpnmonknjnojddfkpgkljpfnnfcklj.crx")) :
new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.EAGER);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
Proxy proxy = new Proxy();
proxy.setHttpProxy("http://proxy.aaaaaaaaaaaaaaaa.com:8080");
proxy.setSslProxy("http:// proxy.aaaaaaaaaaaaaaaa.com:8080");");
proxy.setNoProxy("");
capabilities.setCapability("proxy", proxy);
capabilities.setCapability("enableVNC", true);
capabilities.setCapability("name", String.format("TEST - %s", scenario.getName()));
System.setProperty("selenide.remote","https://grid.aaaaaaaaaaaaaaaa.com/wd/hub");
System.setProperty("selenide.browser", "chrome");
System.setProperty("selenide.proxyHost", "proxy.aaaaaaaaaaaaaaaa.com ");
System.setProperty("selenide.proxyPort", "8080");
System.setProperty("selenide.proxyEnabled", "true");
if (System.getProperty("debugMoon") != null && System.getProperty("debugMoon").length()>0) {
capabilities.setCapability("devtools", true);
capabilities.setCapability("noExit", true);
System.setProperty("devtools", "true");
System.setProperty("noExit", "true");
System.setProperty("moon_debugged", "true");
}
// options.merge(capabilities);
try {
if(mock) { addHeaderMock(); } // adding header before Chromedriver new () when started in the MOON test Grid
logger.info("*********** Grid ***********");
final URL url = new URL("https://grid.aaaaaaaaaaaaaaaa.com/wd/hub");
logger.info(">>> Connecting to Moon test grid url: " + url.toString());
driver = new RemoteWebDriver(url, capabilities) ); // have tried both capabilities object but also options.merge(capabilities) with no joy
} catch (final Exception e) {
logger.info("Unable to create driver " + e);
}
logger.info("Connection established\n");
return driver;
}
Any hints or pointers in the right direction are much appreciated!

Getting a Custom Elements using a Chrome Addon Content Script

When I execute this code in the console of a website, it goes well, and reaches the console.log('defined').
However, when I execute it via a chrome extension content script, I keep getting "undefined" in my customElements prints. Why?
const script = document.createElement('script')
script.setAttribute('type', 'module');
script.setAttribute('src', 'https://unpkg.com/pose-viewer#0.2.3/dist/pose-viewer/pose-viewer.esm.js');
document.body.appendChild(script);
while (!window.customElements.get('pose-viewer')) {
await new Promise(resolve => requestAnimationFrame(resolve))
console.log(window.customElements.get('pose-viewer'))
}
console.log('defined')
I can see the script being injected to the page and loaded well via the network tab.
Additionally, if I run this through the chrome extension, and then try window.customElements.get('pose-viewer') in the console, it works.
Load it via custom loader and inject to verify customelements
In Content Script
const script = document.createElement('script');
script.setAttribute('src', chrome.extension.getURL("js/customloader.js"));
document.body.appendChild(script);
And the js/customloader.js
const script = document.createElement('script')
script.setAttribute('type', 'module');
script.setAttribute('src', 'https://unpkg.com/pose-viewer#0.2.3/dist/pose-viewer/pose-viewer.esm.js');
script.onload = function() {
verifyCustomElements().then(fn => {
console.log('defined')
console.log(window.customElements)
})
}
document.body.appendChild(script);
async function verifyCustomElements(){
while (!window.customElements.get('pose-viewer')) {
await new Promise(resolve => requestAnimationFrame(resolve))
consol.log("checking")
console.log(window.customElements.get('pose-viewer'))
}
}
The defined now is ready to do customElements Stuff Now :)
Check if adding tabs to the list of permissions solves it.

selinium-webdriver issue with Error: The geckodriver.exe executable could not be found on the current PATH

Hey I want to get screen shot with nodejs selinium-webdriver firefox
I am getting error like that : Error: The geckodriver.exe executable could not be found on the current PATH.
I set up the enviornment variable, but no luck
You need to set the path to the geckodriver.exe prior to creating the driver instance.
In Java:
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");//"<PATH TO LOCATION>\\chromedriver.exe");
I had some successful result with this process:
1° - Check if your webdriver(geckodriver, chromedriver, etc.) is in the correct path (if you don't know how to do it, check the link, https://www.youtube.com/watch?v=fj0Ud16YJJw). I think this video is a little old, because in npm the code information is different, updated, but it also serves as instruction.
2°- I changed my type of license(in package.json) from “ISC” to “MIT”, you can do this manually. And for my surprise, this change made my code go well.
const webdriver = require("selenium-webdriver");
const firefox = require("selenium-webdriver/firefox");
const { Builder, Browser, By, Key, until } = require("selenium-webdriver");
async function example() {
let driver = await new Builder().forBrowser(Browser.FIREFOX).build();
try {
await driver.get("https://www.google.com/ncr");
await driver.findElement(By.name("q")).sendKeys("Selenium", Key.RETURN);
await driver.wait(until.titleIs("webdriver - Google Search"), 1000);
} finally {
await driver.quit();
}
}
example();
And here we have another link that goes to selenium webdriver dependency in npm website(https://www.npmjs.com/package/selenium-webdriver) for more information.

Protractor error : BUG: launcher exited with 1 tasks remaining for my simple first test

I run the below simple config/step and feature file for my first protractor test which is trying to recognize my feature file and console output.
I am getting the error BUG: launcher exited with 1 tasks remaining.
I am not sure what is going on here. Some help is appreciated.
Feature file
Feature: Verify the Test Room Javascript application
Scenario: Check the input text field
Given I go to Test Run Application TC001
When I enter text on the Input field TC001
Step file
module.exports = function (){
this.Given(/^I go to Test Run Application TC001$/, function(){
browser.ignoreSynchronization = true;
browser.get("https://www.thetestroom.com/jswebapp/");
browser.sleep(8000);
console.log("The testroom application opened");
callback();
});
this.When(/^I enter text on the Input field TC001$/, function() {
console.log("Trying to find the input field");
});
and my config file:
exports.config = {
chromeDriver: '/usr/local/lib/node_modules/protractor/selenium/chromedriver',
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'cucumber',
capabilities: {
browserName: 'chrome'
},
specs: ['testrun.feature'],
cucumberOpts: {
require: ['testrun_steps.js'],
}
}
I get the below error when I run the testrun_conf.js
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Feature: Verify the Test Room Javascript application
Scenario: Check the input text field # testrun.feature:3
The testroom application opened
[launcher] BUG: launcher exited with 1 tasks remaining
Make sure you are not using something like:
this.AfterFeatures(function() {
browser.close(); // not required
});

Resources