Unable to create Headless Chrome Instance with ChromeDriver and NodeJS - selenium

I am using NodeJS Selenium, Mocha and Chai to run test automation. I have spent several hours trying to get Chrome to run "headless" I use the function below to create a driver instance. When Chrome opens it is neither headless not maximized. Tested on both Windows with Chrome 76 and OSX with Chrome 74.
export async function getDriver() {
let options = new chrome.Options();
options.addArguments("--window-size=1024,768");
options.addArguments("--disable-gpu");
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
options.addArguments("--headless");
var driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
return driver;
}

do you try
const options = new chromeDriver.Options();
options.setChromeBinaryPath(CHROME_BIN_PATH);
options.addArguments( 'headless', 'disable-gpu');
or just
let chromeOptions = {
'args': ['--headless', '--disable-gpu'] };
chromeCapabilities.set('chromeOptions', chromeOptions);
const driver = new webdriver.Builder().withCapabilities(chromeCapabilities).build()

Related

How to test Electron app using selenium and java

Hi Im having an issue with testing an electron app. Up until last week our product was ran on chrome. But now the product has been changed to an electron desktop app and when launched the window isnt picked up.
The flow is basically I open the product on chrome and it appears as a pop up. Previously this was just a chrome pop up but now its an electron app. And now i cnat seem to switch to this window. Im wondering is it possible to switch between the two or do i need a different driver and just test he electron app by itself?
My driver factory is shown here
public class DriverFactory {
private static WebDriver driver;
public static WebDriver startDriver() {
String projectLocation = System.getProperty("user.dir");
// add in elements for logging into the mobile application also - Android and
// iOS.
if (OSValidator.isMac()) {
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver_mac");
} else if (OSValidator.isWindows()) {
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
} else {
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver_linux");
}
if (System.getProperty("app.env") != null) { // If coming from Jenkins/Maven goal..
// This is for logging results. Added when investigating crashes on chrome driver. Can be disabled when not needed. 26/03/2020
System.setProperty("webdriver.chrome.verboseLogging", "true");
}
unknown-error-devtoolsactiveport-file-doesnt-exist-while-t
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
options.addArguments("--window-size=1920x1080");
options.addArguments("--disable-cache");
//options.addArguments("--headless");
options.addArguments("--disable-application-cache");
options.addArguments("--disk-cache-size=0");
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--dns-prefetch-disable");
//options.addArguments("--no-sandbox"); // Bypass OS security model
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
driver = new ChromeDriver(options);
//--------------------
return driver;
}
}
It is described here.
https://applitools.com/blog/automating-electron-applications-using-selenium/
You just need to set appropriate options and use same code for the chrome and electron.
#Before
public void setup() {
ChromeOptions opt = new ChromeOptions();
opt.setBinary("/Users/yanir/Downloads/Electron API Demos.app/Contents/MacOS/Electron API Demos");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("chromeOptions", opt);
capabilities.setBrowserName("chrome");
driver = new ChromeDriver(capabilities);
if (driver.findElements(By.id("button-about")).size() > 0)
driver.findElement(By.id("button-about")).click();
}

Running headless Firefox WebDriver on Jenkins (Windows OS)

My test cases involve export/download the excel files from web pages. For which I am using Firefox profile to accept the downloads when the download dialog popup on windows. The following code is working when I execute my test on local windows.
ProfilesIni profile = new ProfilesIni();
FirefoxProfile fProfile = profile.getProfile("Selenium");
fProfile.setPreference("browser.download.folderList", 2);
fProfile.setPreference("browser.download.manager.showWhenStarting", false);
fProfile.setPreference("browser.download.dir", "C:\\temp\\reports\\");
fProfile.setPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
fProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
fProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
fProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
fProfile.setPreference("browser.download.manager.focusWhenStarting", false);
fProfile.setPreference("browser.download.manager.useWindow", false);
fProfile.setPreference("browser.download.manager.showAlertOnComplete", false);
fProfile.setPreference("browser.download.manager.closeWhenDone", false);
fProfile.setAcceptUntrustedCertificates(true);
fProfile.setAssumeUntrustedCertificateIssuer(true);
fProfile.setPreference("security.insecure_field_warning.contextual.enabled", false);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, fProfile);
capabilities.setCapability("marionette", true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setAcceptInsecureCerts(true);
driver = new FirefoxDriver(capabilities);
I want to run the tests on Jenkins and I have been running into the issues. I receive Nullpointer exception on the line right after I initialize the firefox profile. Which means the firefox profile did not pickup. Following is the error.
I am wondering if Jenkins is not understanding the firefox profile "Selenium" which I created through Firefox Profile section.
Note: I can run my tests from the windows command line but not through the Jenkins.
Any help is highly appreciated.
Instead of using capabilities, use FirefoxOptions
FirefoxOptions options = new FirefoxOptions();
options.addArgument("--headless");
WebDriver driver = new FirefoxDriver(options);

How to Set capability for IE browser to run in Headless mode

I want to run the scripts in Headless mode for all the 3 browsers Chrome, Firefox & IE
The following is the code for Chrome:
System.setProperty("webdriver.chrome.driver", "./drive/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("window-size=1400,600");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com/");
Note : Its working fine
Firefox:
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
System.setProperty("webdriver.gecko.driver", "./drive/geckodriver.exe");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://www.google.com/");
Note : Its working fine
IE:
Similarly i want to execute in IE with options
IE does not have support for a headless mode (since IE nowadays does not recieve any kind of update or improvements.).
But you can use trifle.js, a kind of browser that can emulate some IE versions in a headless mode, since its coded as a port of PhantomJS.

Not able to open Chrome headless from Selenium

I am using maven here.Here is my Selenium code:
DesiredCapabilities capb = DesiredCapabilities.chrome();
capb.setCapability("chrome.binary","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless","--disable-gpu", "--no-sandbox","--remote-debugging-port=9222");
capb.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty("webdriver.chrome.driver","/Users/nitinkumar/TEST/chromedriver");
try{
ChromeDriver driver = new ChromeDriver(capb);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://qa.cmnetwork.co");
driver.quit();
}
catch(Exception e)
{
e.printStackTrace();
}
when I run "mvn test" it starts the chrome in GUI mode. but It should open in Headless mode. I have chrome vesrion 59.0, OS X yosemite(10.10.5), chromedriver 2.30 and Selenium 3.4.0.
It won't open in GUI mode. Just the chrome launcher icon will be opened. And it is an expected behaviour.
You have to remove the argument --remote-debugging-port. That will block the launched headless Chrome. So the script will never move forward.And you will get a chrome not reachable error
So change the arguments like
options.addArguments("--headless","--disable-gpu", "--no-sandbox");
Also, there is no need for --no-sandbox. As per Official doc only --headless and --disable-gpu flags are enough
Unless you have multiple versions of chrome installed, there is no need for DesiredCapabilities as well.
So the simple code for headless-chrome
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless","--disable-gpu");
System.setProperty("webdriver.chrome.driver","/Users/nitinkumar/TEST/chromedriver");
ChromeDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://qa.cmnetwork.co");
driver.quit();

How to click Allow on Show Notifications popup using Selenium Webdriver

I'm trying to login to Facebook. After a successful login, I get a browser popup:
How with the webdriver can I click Allow and proceed forward?
Please Follow below steps :
A) USING JAVA :
For Old Chrome Version (<50):
//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();
//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");
//Set path for driver exe
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");
//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);
For New Chrome Version (>50):
//Create a map to store preferences
Map<String, Object> prefs = new HashMap<String, Object>();
//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);
//Create an instance of ChromeOptions
ChromeOptions options = new ChromeOptions();
// set ExperimentalOption - prefs
options.setExperimentalOption("prefs", prefs);
//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);
For Firefox :
WebDriver driver ;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("permissions.default.desktop-notification", 1);
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
driver = new FirefoxDriver(capabilities);
driver.get("http://google.com");
B) USING PYTHON :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
option = Options()
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")
# Pass the argument 1 to allow and 2 to block
option.add_experimental_option(
"prefs", {"profile.default_content_setting_values.notifications": 1}
)
driver = webdriver.Chrome(
chrome_options=option, executable_path="path-of-driver\chromedriver.exe"
)
driver.get("https://www.facebook.com")
C) USING C#:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-notifications"); // to disable notification
IWebDriver driver = new ChromeDriver(options);
import unittest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time
class SendMsgSkype(unittest.TestCase):
#classmethod
def setUpClass(cls):
options = Options()
options.add_argument("--disable-notifications")
cls.driver = webdriver.Chrome("./chromedriver.exe", chrome_options=options)
cls.driver.implicitly_wait(5)
cls.driver.maximize_window()
cls.driver.get("https://web.skype.com/ru/")
It works for me.
More details here: http://nullege.com/codes/show/src#t#a#TardyParty-HEAD#oxbiz.py/21/selenium.webdriver.Chrome
This not an alert box, so you can't handle it using Alert, this is a chrome browser notification, To Switch off this browser notification you need to create chrome preference map with chrome option as below :
//Create prefs map to store all preferences
Map<String, Object> prefs = new HashMap<String, Object>();
//Put this into prefs map to switch off browser notification
prefs.put("profile.default_content_setting_values.notifications", 2);
//Create chrome options to set this prefs
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
//Now initialize chrome driver with chrome options which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);
//Now do your further steps
Hope it helps..:)
The one and only working solution I've come across so far is this:
from selenium.webdriver.chrome.options import Options
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
no answer has been accepted yet, this following code works for me
ruby, rspec, capybara
Capybara.register_driver :selenium_chrome do |app|
prefs = {"profile.managed_default_content_settings.notifications" => 2,}
caps = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options: { prefs: prefs })
Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: caps)
end
Capybara.javascript_driver = :selenium_chrome
try {
// Check the presence of alert
Alert alert = driver.SwitchTo().Alert();
// if present consume the alert
alert.Accept();
} catch (NoAlertPresentException ex) {
//code to do if not exist.
}
Facebook authentication window displays an overlay that covers the continue as [username] button.
This makes the continue button un-clickable. To circumvent that problem, you can hide those layers programmatically using JavaScript (not recommended) using this code (don't do this).
// DO NOT USE THIS CODE.
function forceClickSetup(targetSelector) {
return browser.selectorExecute("div",
function(divs, targetSelector) {
var button = document.querySelector(targetSelector);
for(var i = 0; i < divs.length; i++) {
if(!divs[i].contains(button)) {
divs[i].remove();
}
}
return i;
}, targetSelector);
}
Or instead, you can dismiss the notifications dialog, after which facebook will uncover the continue button. But before wildly hitting Escape at the browser, first make sure that the continue button has been shown.
// USE THIS CODE.
browser.waitForVisible("[name=__CONFIRM__]");
browser.keys("Escape"); // Dismiss "notifications" dialog box.
var confirmButtonSelector = "[name=__CONFIRM__]";
This solution is really Matthijs' (see comments above)
if you play with Ruby and Capybara try this code
Capybara.register_driver :chrome_no_image_popup_maximize do |app|
# 2: disable, other than 2 means enable it
preferences = {
"profile.managed_default_content_settings.notifications" => 2,
"profile.managed_default_content_settings.images" => 2,
"profile.managed_default_content_settings.popups" => 2
}
caps = Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {
'prefs' => preferences,
}
)
args = [ "--start-maximized" ]
Capybara::Selenium::Driver.new(app, {:browser => :chrome, :desired_capabilities => caps, :args => args})
end
Capybara.default_driver = :chrome_no_image_popup_maximize
Capybara.javascript_driver = :chrome_no_image_popup_maximize