Setting specific capabilities for selenium webdriver - javascript

I'm trying to set some specific capabilities for a Selenium Webdriver.
In this example i want to change a capability of the webdriver for the Firefox browser. I'm trying to this in Javascript.
this.driver = new selenium.Builder().forBrowser('firefox').build();
I tried things like calling .withCapabilities() but it is not working as i expected it and crashes the program.
In specific i want to set the 'acceptSslCerts' capability to true because it is false in default.
Does anybody have an idea on how to this?
I'm not able to find anything in the API reference or on the internet.

This works fine for me, to set CORS in my chrome browser.
const { Builder, By, Key, until } = require('selenium-webdriver');
const capabilities = {
'chromeOptions': {
'args': ['--disable-web-security', '--user-date-dir']
}
}
let driver = new Builder().withCapabilities(capabilities).forBrowser('chrome').build();

For firefox, through FirefoxProfile, you can accept SSL certificate.
e.g FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setAcceptUntrustedCertificates(true)
For googlechrome, through DesiredCapability, you can set the browser property.

Related

How to add custom header for accessing a page URL and then performing test automation on that page, i am using a webdriverio,mocha,nodejs framework

I have a web page where the functionality changes when a custom header "headerKey": "headervalue" is being set through a chrome extension. While I can do this manually I want to do it through the code in order to do test automation.
Note:-
Please help with the approaches.
There is no functionality in webdriver to perform this operation.
I have used modheader but it is not working.
getModHeaderExtension() {
const filename = path.join(__dirname, "Modify.crx");
console.log(filename);
const stream = fs.readFileSync(filename);
return new Buffer(stream).toString('base64');
}
I know some time passed since the question was added, although it took me some time to figure it out by myself so maybe someone will make use of it.
Add #wdio/devtools-service to your dev dependencies (this should have the same major version as your other #wdio libraries, otherwise you can get some problems)
You need to add devtools to services in wdio.conf.ts:
export const config = {
[...]
services: ['chromedriver', 'devtools']
[...]
}
Now add you can add headers in you test method or wherever you need to:
const encodedCredentials = base64.encode(`${appConfig.basicAuthDevUser.userName}:${appConfig.basicAuthDevUser.password}`);
browser.cdp('Network', 'setExtraHTTPHeaders', {
headers: {
Authorization: `Basic ${encodedCredentials}`,
},
});
More on using devtools with wdio:
https://webdriver.io/docs/devtools-service/
More on chrome specific capabilites:
https://chromedevtools.github.io/devtools-protocol/tot/Network/
I was able to find the solution to pass a custom header while opening my webpage.
I am using ChromeDevTools service which is supported by webdriverio v5, using its method
browser.cdp(domain, command, parameters);
For the domain, command, and parameters please visit devtools protocol below:-
https://chromedevtools.github.io/devtools-protocol/

JavaScript: Disable images in Selenium ChromeDriver

Because Webdriver waits for the entire page to load before going on to the next line, I want to disable images will speed things up when the network is slow.
This is the example js file in Selenium Webdriver's website:
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://www.google.com/ncr');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.findElement(By.name('btnG')).click();
driver.wait(until.titleIs('webdriver - Google Search'), 1000);
driver.quit();
How can I disable image in my code?
I have search google for this question, I only get this solution in Python: Disable images in Selenium Python.
On a high level, I see some solutions:
set profile.managed_default_content_settings.images to 2 (I can't find the corresponding chromedriver documentation, but you can google it).
Set up a proxy. Connect to your page via a proxy that returns empty data when asking for an image file.
load the browser with a browser plugin that does this for you. Something (a bit like ad-blocked works) might be available already. (con: browser-specific solution)
Here I give you code for not loading image.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'profile.managed_default_content_settings.images': 2})
driver = webdriver.Chrome("chromedriver.exe",chrome_options=chrome_options)
You can pass an optionsobject to WebdriverJS' Builder that disables images:
{
prefs: {
profile: {
managed_default_content_settings: {
images: 2
}
}
}
}
The complete example is:
const chromeDesktop = {
prefs: {
profile: {
managed_default_content_settings: {
images: 2
}
}
}
};
const { By, Builder, until } = require('selenium-webdriver');
const driver = new Builder().withCapabilities(chromeDesktop).build();
This definitely worked for me.
import { Options } from 'selenium-webdriver/chrome';
const options = new Options();
options.setUserPreferences({
'profile.managed_default_content_settings.images': 2, //disable loading
});

Retrieving console log from Firefox 43 with Selenium without Firefox extensions

Is it possible to retrieve the browsers console.log with Selenium and Firefox 43? If so, how?
Here are my settings:
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
LoggingPreferences logs = new LoggingPreferences();
logs.enable(LogType.BROWSER, Level.ALL);
logs.enable(LogType.DRIVER, Level.ALL);
logs.enable(LogType.CLIENT, Level.ALL);
logs.enable(LogType.PERFORMANCE, Level.ALL);
logs.enable(LogType.PROFILER, Level.ALL);
logs.enable(LogType.SERVER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
FirefoxBinary binary = new FirefoxBinary(new File(...));
FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(binary, profile, capabilities);
//...doing things with the driver ...
driver.manage().logs().get(LogType.BROWSER) // already tried every LogType
The only output i get from this is something like:
1450878255029 addons.xpi DEBUG startup
...
Error in parsing value for 'display'. Declaration dropped.
But not the output which is written in the browsers javascript console log.
I already tried several FF profile settings like:
profile.setPreference("extensions.sdk.console.logLevel", "all");
profile.setPreference("webdriver.log.file",tempfile.getAbsolutePath());
profile.setPreference("webdriver.firefox.logfile", othertempfile.getAbsolutePath());
profile.setPreference("webdriver.log.driver", "ALL");
Nothing helped so far.
In Chrome this is working flawlessly.
Selenium version: 2.48.2
Firefox version: 43.0.2
I had the same issue. I only got all that log noise about css, security, network and what not, but not what was actually logged by the app through console.log. I am using the same version for webdriver and firefox you do. For other browsers this was not a problem.
I ended up extending my client code with custom log recording. Speaking in wire protocol terms:
use execute to put something like the following into the client
window.recordedLogs = [];
console.log = function (message) {
if (typeof message === 'object') {
message = JSON.stringify(message);
}
window.recordedLogs.push(message);
};
use execute to retrieve window.recordedLogs
Warning: the above code is very simplistic, it does not take care of multiple messages passed to the log method, nor does it handle other log methods like info, error, etc.
However it can be a good multi-browser-compliant alternative to the wire protocol log method.

How to automatically accept SSL certs in chrome?

Its been a while I'm trying to figure out a way to automatically accept SSL certs. But unfortunately no luck. So, here is the case, I'm working on selenium tests. And, every time when I run the test on chrome, a small pop-up appears asking to select a certificate.
I tried this in python: How to deal with certificates using Selenium?
I also tried (in javascript):
var options = new chrome.Options();
options.addArguments("--ignore-certificate-errors")
But it doesn't seems to work!
In firefox, there is an option to automatically selects certs. Is there any way in selenium or in chrome settings which automatically selects the certs? Will ENTER/RETURN keys in selenium work?
EDITED: Below is my code. Is this the right way to use?
var launch = function(){
var options = new chrome.Options();
options.addArguments("--test-type");
/* Also tried options.addArguments(“--ignore-certificate-errors")
*/
var driver = new webdriver.Builder()
.usingServer('http://127.0.0.1:4444/wd/hub')
.setChromeOptions(options)
.build();
driver.get(url)
}
P.S Here, I'm using JavaScript.
ACCEPT_SSL_CERTS is one of the browser's desired capability that tells the browser to accept / deny ssl certificates by default.
below is a sample code for accepting SSL certificates in chrome:
DesiredCapabilities cap=DesiredCapabilities.chrome();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.chrome.driver","Chrome driver path");
// Open browser with capability
WebDriver driver=new ChromeDriver(cap);
It is major problem with Chrome versions above v.80.
I am currently using version 84.0.4147.105 which won't accept or ignore SSL certificate.
The one thing to do is to downgrade Chrome version below v.80, especially for those of you who are building test cases in local Host applications.
Example using Selenium-grid and Chrome
const { Builder, until, By } = require("selenium-webdriver");
const capabilities = {
browserName: "chrome",
acceptInsecureCerts: true,
};
// alternative require `Capabilities` and do like this:
// const capabilities = Capabilities.chrome().setAcceptInsecureCerts(true);
try {
const driver = await new Builder()
.usingServer("http://localhost:4444/wd/hub")
.withCapabilities(capabilities)
.build();
await driver.get("https://frontend");
// tests
const el = await driver.wait(until.elementLocated(By.id("root")), 2000);
await driver.wait(until.elementIsVisible(el), 2000);
expect(el).not.toBeNull();
// tear down
await driver.quit();
} catch (err) {
throw new Error(err);
}
chrome_options = ChromeOptions()
chrome_options.add_argument('--lang='+language)
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
chrome_options.add_argument('--disable-web-security')
chrome_options.add_experimental_option('useAutomationExtension', False)
if headless :
chrome_options.set_headless()
if remote :
self.driver = webdriver.Remote(command_executor=wd,desired_capabilities=chrome_options.to_capabilities(),options=chrome_options)
else:
self.driver = webdriver.Chrome(desired_capabilities=chrome_options.to_capabilities(),options=chrome_options)

Unable to sendkeys using webdriverjs specifically F11 to maximise the browser

With the below code block it opens a chrome browser fine it just won't full screen the browser using F11. i used to use C# and selenium and that worked fine using this method on chrome and different browsers. It finds the element 'body' but then does not send the key press. Am I doing something wrong here that i should be requiring some other library?
the documentation for webdriverjs is pathetic and there is very few examples, I am seriously considering dumping it for something else possibly python.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('https://www.google.co.uk/');
driver.wait(function () {
return driver.getTitle().then(function (title) {
return title === 'Google';
});
}, 1000);
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys("F11");
why are we doing this. we are developing a website that will change depending on size 800x600 + with and without the toolbar depending on how the screen is used different items will be displayed. i can maximise the window using,
driver.manage().window().maximize();
This however still leaves the toolbar present and doesn't act as if the user has pressed the F11 key.
it tooks some time to find it but you should have all the Keys in webdriver.Key
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys(webdriver.Key.F11);
Hope it helps!
A co-worker has just discovered that it works well in C# with:
Driver.Instance.Manage().Window.FullScreen();
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).send_keys(Keys.F11).perform()
I use a similar command to toggle JS via Firefox's NoScript add-on
edit: I just tested, and it works!
This should work for you:
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys(Keys.F11);
You can maximise the window using:
driver.manage().window().maximize();
For me the one emulating correctly the F11 on startup is:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");
WebDriver driver = new ChromeDriver(options);
Or if the kiosk mode is preferred:
ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk");
WebDriver driver = new ChromeDriver(options);

Categories

Resources