The Selenium Firefox WebDriver does not start the installed extension - java

I have:
Selenium Firefox WebDriver v.3.8.1
Browser Firefox 43
XPI-file with firefox add-on
I ran the extension in the browser in two ways: jpm and using the program on the java through selenium firefox web-driver.
In the first case, I run command jpm run, which creates a new profile with the extension installed and running. It is important that the extension is automatically launched immediately after opening the browser.
I need to achieve the same result, but with the help of the selenium webdriver. As a result of my program, a profile is created with the extension installed, but the extension does not start the same way as when executing the jpm run command.
Help, please, understand what can be the problem.
My code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.FirefoxBinary;
import java.io.File;
import org.openqa.selenium.remote.DesiredCapabilities;
public class MyClass extends Thread {
private String baseUrl;
public MyClass(String baseUrl) {
this.baseUrl = baseUrl;
}
public void run() {
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File("C:\\switcher.xpi"));
profile.setPreference("extensions.#switcher.sdk.load.command", "run");
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver = new FirefoxDriver(caps);
driver.get(this.baseUrl);
}
public static void main( String[] args){
System.setProperty("webdriver.firefox.marionette",
"C:\\geckodriver.exe");
Thread t1 = new MyClass("http://google.com");
t1.start();
}
}
P.S. I tried to install the firebug with the help of a selenium webdriver - the problem is the same.

I had the same issue as you. Desired capabilities are deprecated. The way to go is FirefoxOptions.
private void initializeFirefoxDriver() {
//set the location to your gecho driver
System.setProperty("webdriver.gecko.driver", USER_DIRECTORY.concat("\\drivers\\geckodriver.exe"));
//instantiate the Firefox profile
FirefoxProfile profile = new FirefoxProfile();
//Adding the location to the extension you would like to use
profile.addExtension(new File("Path_T0_Your_Saved_Extention\\try_xpath-1.3.4-an+fx.xpi"));
//Setting the preference in which firefox will launch with.
profile.setPreference("permissions.default.image", 2);
//instantiating firefox options.
FirefoxOptions options = new FirefoxOptions();
//Passing the profile into the options object because nothing can ever be easy.
options.setProfile(profile);
//passing the options into the Firefox driver.
webDriver = new FirefoxDriver(options);
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
The code is not complete and just a snippet, but that will start an extension of your choice. Firebug is no more as well so maybe look at TruePath and Find Path extensions. H
Hope this helped.

Related

Headless chrome using Selenium-Java running tests in normal UI mode of browser

I am trying to run my application in headless mode using Chrome Browser, Selenium and Java. But it open a new chrome instance and start running the script in normal UI mode(can see the execution)
Is there anything wrong in code or browser compatibility.
OS - Windows 10,
Chrome Version - 85.0.4183.121
Below is my code -
package XYZ;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Test{
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\TestUser\\Desktop\\SeleniumWorkspace\\ABC\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("window-size=1400,800");
options.addArguments("disable-gpu")
//options.addArguments("--headless", "--disable-gpu", "--window-size=1400,800","--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com");
System.out.println(driver.getCurrentUrl());
}
}
I can see you are missing "--" before passing the arguments in the code. Below is the correct code to use headless chrome while running your automated cases:
package XYZ;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Test{
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\TestUser\\Desktop\\SeleniumWorkspace\\ABC\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
options.addArguments("--window-size=1400,800");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com");
System.out.println(driver.getCurrentUrl());
}
}
For me this is working fine. I hope this solves your probelm.

Timeout exception when using dev tools with selenium-java-4.0.0 and chromedriver v85

I'm trying to use selenium dev tools java API, and for multiple API methods I'm getting java.util.concurrent.TimeoutException.
For example I'm trying to use Network.clearBrowserCache, which should work accroding to chromedriver docs: https://chromedevtools.github.io/devtools-protocol/tot/Network/
I'm calling clearBrowserCache using following code:
chromeDriver.getDevTools().send(Network.clearBrowserCache())
It fails, but at the same time if I use other devTools commands like this:
chromeDriver.getDevTools().send(Browser.getVersion())
It returns data properly.
Chrome version is: 85.0.4183.39
Chromedriver version is: 85.0.4183.87
Selenium-java version is: 4.0.0-alpha-6
Try calling createSession before calling clearBrowserCache.
Using your setup, this works:
chromeDriver.getDevTools().createSession();
chromeDriver.getDevTools().send(Network.clearBrowserCache())
and this produces java.util.concurrent.TimeoutException:
chromeDriver.getDevTools().send(Network.clearBrowserCache())
You can verify that the browser cache has been cleared with this snippet:
ChromeDriver driver = new ChromeDriver();
driver.get("https://refreshyourcache.com/en/cache-test/");
Thread.sleep(2000);
driver.getDevTools().createSession();
driver.getDevTools().send(Network.clearBrowserCache());
driver.get("https://refreshyourcache.com/en/cache-test/");
Thread.sleep(5000);
If you run the code, the pages displayed in the test browser will show these images:
If you commment out the line driver.getDevTools().send(Network.clearBrowserCache()); then you get a different result:
Using Selenium 4.0.0-alpha-6, Chrome v85 and ChromeDriver v85.0 through google-chrome-devtools you must be able to use getVersion() method as follows:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.browser.Browser;
public class BrowserGetVersion {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
ChromeDriver driver = new ChromeDriver(options);
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Browser.getVersion());
}
}
Similarly, using the clearBrowserCache() method you should be able to clear the browser cache using the following code block:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
public class ClearChromeCache {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
ChromeDriver driver = new ChromeDriver(options);
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.clearBrowserCache());
driver.get("https://www.google.com/");
}
}
Additional Consideration
Additionally, you can also use setCacheDisabled(true) to completely disable the cache as follows:
Code Block:
import java.util.Collections;
import java.util.Optional;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.testng.Assert;
import org.testng.annotations.Test;
public class testngBasic {
#Test
public void foo() {
System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
ChromeDriver driver = new ChromeDriver(options);
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.clearBrowserCache());
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.of(100000000)));
devTools.send(Network.setCacheDisabled(true));
devTools.addListener(Network.responseReceived(), responseReceived -> Assert.assertEquals(false, responseReceived.getResponse().getFromDiskCache()));
driver.get("https://www.google.com/");
}
}
This usecase
Possibly your code have nothing to do with java.util.concurrent.TimeoutException error and the real issue is either with the:
jdk version
guava version
Solution
Ensure that:
JDK is upgraded to current levels JDK 8u252.
guava is upgraded to guava-29.0-jre.
Outro
Disable cache in Selenium Chrome Driver
It worked fine
public void testCdt {
final ChromeLauncher launcher = new ChromeLauncher();
final ChromeService chromeService = launcher.launch(false);
final ChromeTab tab = chromeService.createTab();
final ChromeDevToolsService devToolsService = chromeService.createDevToolsService(tab);
final Page page = devToolsService.getPage();
Network network = devToolsService.getNetwork();
// Clear browser cached
network.clearBrowserCache();
// Log requests with onRequestWillBeSent event handler.
network.onRequestWillBeSent(
event ->
System.out.printf(
"request: %s %s%s",
event.getRequest().getMethod(),
event.getRequest().getUrl(),
System.lineSeparator()));
network.onLoadingFinished(
event -> {
chromeService.closeTab(tab);
launcher.close();
});
network.enable();
page.navigate("http://github.com");
devToolsService.waitUntilClosed();
}

How can I open the Chrome browser in mobile mode using the Selenium webdriver for load testing in JMeter?

I want to open a URL in the Chrome browser, but in mobile mode during my load test in JMeter. I am using Selenium scripts. Below is my Selenium script
var pkg = JavaImporter(org.openqa.selenium,org.openqa.selenium.support.ui) // Import Java Selenium packages
var Thr = JavaImporter(java.lang.Thread) // Import Thread sleep packages
var wait = new pkg.WebDriverWait(WDS.browser,30) // Import WebDriverWait Package
WDS.sampleResult.sampleStart()
WDS.browser.get('https://xyz=${__urlencode(${token})}');
WDS.sampleResult.sampleEnd()
Below is the Java class I have created in BeanShell Preprocessor in Jmeter to use Chromeoptions to open Chrome in mobile mode, but I don't know how I can call it in webdriver above and I am doing it correctly or not:
public class page {
public static void main (String args[]) {
String device = "Samsung Galaxy S4";
//options.ChromeOptions options = new ChromeOptions();
ChromeOptions options = new ChromeOptions();
options.EnableMobileEmulation(device);
IWebDriver driver = new ChromeDriver(options);
}
}
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language
There is no EnableMobileEmulation function in ChromeOptions, you should be using setExperimentalOption instead
Example code for the JSR223 Sampler:
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver.exe");
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Galaxy S5");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("mobileEmulation", mobileEmulation);
ChromeDriver driver = new ChromeDriver(options)
driver.get("http://example.com");
log.info(driver.getTitle());
driver.quit();

How to use SSL certificates in Selenium Web Driver?

I'm using Selenium Web Driver on Windows 7.
I'm trying to test a website that use authentication and I need to use SSL certificates.
When I use Firefox out of Selenium all works fine but I've noted that the Firefox browser session opened by Selenium doesn't have any certificates registered and so it's clear that it doesn't work.
Here you are the Advanced Preferences when I use Firefox "out" of Selenium
and here you are the same when I use the Firefox sessione opened by Selenium
I've tried to keep the session opened and to register manually the certificate but the browser session doesn't register the certificate.
Here you are my code if could be useful
package myTestProjects;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GAMOPERA_Test_01 {
private static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
// Create a new instance of the Firefox driver
System.out.println("Creo una nuova sessione del browser Firefox ...");
driver = new FirefoxDriver();
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// It is always advisable to Maximize the window before performing DragNDrop action
System.out.println("Massimizzo la finestra del browser ...");
driver.manage().window().maximize();
Thread.sleep(3000L);
//Launch the Sistema Piemonte Home Page
System.out.println("Mi collego a Sistema Piemonte ...");
driver.get("http://<my_site_url>");
Thread.sleep(3000L);
// Find the element Accedi o
System.out.println("Accesso tramite certificato digitale ...");
driver.findElement(By.xpath("/html/body/div[6]/div/div/div[2]/form/table/tbody/tr[3]/td/input")).click();
//driver.findElement(By.className("loginbutton")).click();
Thread.sleep(3000L);
// Print TEST = OK!!
System.out.println("TEST = OK !!");
//driver.quit();
}
}
Any suggestions?
I've solved!
Surfing on the web I've found this post http://seleniummonk.blogspot.it/p/how-to-handle-ssl-cerificates.html that gave me the solution.
I need to use the "Firefox profile" (I use the default one ...), so I can have all the certificates I need to.
Here you're the new code that works
package myTestProjects;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class GAMOPERA_Test_01 {
private static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffProfile = profile.getProfile("default");
// Create a new instance of the Firefox driver
System.out.println("Creo una nuova sessione del browser Firefox ...");
driver = new FirefoxDriver(ffProfile);
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// It is always advisable to Maximize the window before performing DragNDrop action
System.out.println("Massimizzo la finestra del browser ...");
driver.manage().window().maximize();
Thread.sleep(3000L);
//Launch the Sistema Piemonte Home Page
System.out.println("Mi collego a Sistema Piemonte ...");
driver.get("<my_site_url>");
Thread.sleep(3000L);
// Find the element Accedi o
System.out.println("Accesso tramite certificato digitale ...");
driver.findElement(By.xpath("/html/body/div[6]/div/div/div[2]/form/table/tbody/tr[3]/td/input")).click();
//driver.findElement(By.className("loginbutton")).click();
Thread.sleep(3000L);
// Print TEST = OK!!
System.out.println("TEST = OK !!");
//driver.quit();
}
}
I hope this could be useful!
You can do that using Proxy. Through DesiredCapabilities you can configure the browser accordingly.
String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new InternetExplorerDriver(cap);
Code taken from SeleniumHQ
First create a profile as I created with "Test" in Firefox using below command in CMD:
"C:\Program Files\Mozilla Firefox\firefox.exe" -P
Then import your certificate in this newly created Firefox Profile with Password used to generate the certificate.
In my case this was a P12 extenstion Certificate.
Once done you can use below code in Selenium and Firefox will not popup for Certificate and you will be logged into the Portal or Website.
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile myProfile = allProfiles.getProfile("Test");
myProfile.setPreference("security.default_personal_cert", "Select Automatically");
FirefoxOptions firefoxoptions = new FirefoxOptions();
firefoxoptions.setProfile(myProfile);
WebDriver driver = new FirefoxDriver(firefoxoptions);
Background I am using Firefox 56.0 and Windows 7

Unable to start Internet Explorer or Chrome in Selenium Webdriver (JAVA)

I am trying to start up an IE instance using Webdriver. I can't figure out why I'm receiving these errors, my code appears to be identical to every example I can find on the web.
I'm using Java and testng.
Here is the code:
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
The following errors are displaying, all of these errors are on the "System.setProperty" line.
Multiple markers at this line
- Syntax error on token ""webdriver.ie.driver"", invalid
FormalParameterList
- Syntax error on token(s), misplaced construct(s)
- Syntax error on tokens, FormalParameter expected instead
Please note that I have the exact same problem if I try to use Chrome with this code:
File file = new File("C:/selenium/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
You are running your code from inside class instead of running it from inside method. Covert it to something like
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
public static void main(String[] args) { // <-- you need a method!
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
}
try this :
I'm using "mvn test" to lunch the test process so the path of the IE driver may be changed
File file = new File("classes/tools/IEDriverServer.exe");
Use IE driver with Capabilities
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
caps.setCapability("ignoreZoomSetting", true);
caps.setCapability("nativeEvents", false);
WebDriver driver = new InternetExplorerDriver(caps);
It may help you :)
Actually, on the updated eclipse version, you might have to use #suppressWarnings
package Login;
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Login {
public static void main(String[] args) {
File file = new File("C:\\Users\\IEDRiverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
#SuppressWarnings("unused")
WebDriver driver = new InternetExplorerDriver();
}
}
Simple example:
public class IE {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.ie.driver", "D:\\Sathish\\soft\\SELENIUM\\LatestDownloads\\selenium\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("abc");
driver.close();
}
}
Do the below process.
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
if (browserName.equalsIgnoreCase("InternetExplorer")) {
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe");
caps.setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
caps.setCapability("nativeEvents", false);
browser = new InternetExplorerDriver(caps);
Then after, In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value,
either checked or unchecked, for each zone.
I have applied the same thing at my end, it works fine.

Categories

Resources