Get Firefox Profile Name at Runtime and Set preferrence - firefox

I have a scenario to handle where I am opening Firefox browser using Selenium Webdriver and each time it opens up a new profile. Code is written below:
WebDriver driver = new FirefoxDriver();
Each time it opens up a new profile which is something like : anonymous8958670169066009851webdriver-profile and profile name changes every time WebDriver opens up a Firefox browser. My intention is to get the profile name at runtime and set some preferences on it like handling unresponsive JS alert etc. Basically flow will look like something below:
WebDriver driver = new FirefoxDriver();
<Write some code here to get Firefox profile name>
<Set profile settings like **profile.setPreference("extensions.firebug.currentVersion", "1.8.1");>
Please help me in the second step i.e. Write some code here to get Firefox profile name if anyone already achieved something similar before.

You're approaching the problem backward. The correct thing to do is to create the FirefoxProfile object yourself, and using it in the constructor to the FirefoxDriver. The code would look something like this:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("extensions.firebug.currentVersion", "1.8.1");
WebDriver driver = new FirefoxDriver(profile);

Related

Browser Session testing with Selenium WebDriver

I have following scenario to automate :
User Logs in to a website. Navigates to a certain page on website
Save the url for that page.
Close browser
Open the browser again and navigate to the saved url.
User should be able to see the page without logging in.
I can automate first 3 steps. But when I open browser again in step 4, a new session is started and my user sees log in page.
I believe the web driver browser is in incognito mode. So session cookie is not stored.
Is there any way to automate this scenario using selenium web driver?
It's because every time when you invoke browser, selenium opens a new browser profile..so your cookies will be lost..
You can inject cookies for the second time..
Cookie ck = new Cookie("name", "value");
driver.manage().addCookie(ck);
Or you can use same browser profile for driver..
FirefoxBinary binary = new FirefoxBinary();
File firefoxProfileFolder = new File("/Users/xxx/work/xxx/selenium/src/test/resources/firefoxprofile");
FirefoxProfile profile = new FirefoxProfile(firefoxProfileFolder);
webDriver driver= new FirefoxDriver(binary, profile);
You have to quit the webdriver before launching the saved url.
At 3rd step write driver.quit(); and at 4th step write:
driver.get("<saved_url>");

Firefox pop up obscures the screen paritally in selenium test

I ran my test in BrowserStack and here is an example outcome
How can I turn off this behaviour of Firefox in a selenium test via DesiredCapabilities?
I want to be able to drive this behaviour with settings instead of adding code for a specific browser.
This prompt is related to firefox health report, you can disable it in as: (in java)
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("datareporting.healthreport.uploadEnabled", false);
profile.setPreference("datareporting.healthreport.service.enabled",
false);
profile.setPreference("datareporting.healthreport.service.firstRun",
false);
WebDriver driver = new FirefoxDriver(profile);

How to relaunch firefox browser using WebDriver while retaining the previous session id

There is a bug in my app wherein Logout doesn't work. I need to workaround this issue in my automation that is in Java using WebDriver. The workaround is to close the browser and reopen it and open the Login page.
To automate this workaround, here is what I have tried:
browserDriver.quit();
browserDriver = new FirefoxDriver(capabilities);
browserDriver.get(loginPageURL);
This returns a new session id. Is there a way to retain the previous session id and set it back. I can get the previous session id using
((RemoteWebDriver)browserDriver).getSessionId();
I also tried deleting all the cookies for the current domain using the following code, but the user was still logged in.
browserDriver.manage().deleteAllCookies();
browserDriver.navigate().refresh();
browserDriver.get(loginPageURL);
Appreciate any help on this.
Up to my knowledge after calling the quit() method on driver it will not retain the previous session id.
Anyway try to launch the browser using specific firefox profile by disabling cache in that.
FirefoxProfile profile = new ProfilesIni().getProfile(profilePath);
profile.setPreference("browser.cache.disk.enable", false);
profile.setPreference("browser.cache.memory.enable", false);
profile.setPreference("browser.cache.offline.enable", false);
profile.setPreference("network.http.use-cache", false);
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, profile);
driver = new FirefoxDriver(dc);
driver.get(url);
Firefox Profile creation ==>
https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles
Edit-I
Change below setting in that profile
In "about:config" you can set "Browser.sessionstore.enabled" to false, in which case firefox will not restore your browsing session after it closed.
When you either use
driver.quit();
or
driver.close();
Selenium always starts a new session. This means it's always directs you to the 'Login' page.
Just use below piece of code, no need to set capabilities.
browserDriver.quit();
browserDriver.get(loginPageURL);
You will see the Login page.

What profile does Selenium WebDriver use by default?

Where does Selenium WebDriver (a.k.a Selenium 2) get the anonymous profile that it uses when it opens FirefoxDriver? If it used the default for Firefox, %appdata%/roaming/mozilla/firefox/profiles, then if I were to disable a firefox plugin, it should be disabled for Selenium WebDriver also, so why isn't it?
I will answer it, supporting comment from #twall: When starting firefox in Selenium 2 WebDriver, it starts new, anonymous profile.
However, if you want to change it, you can create new Firefox profile and name it somehow, you know what it is - e.g. SELENIUM
Then in your code do this:
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("SELENIUM");
WebDriver driver = new FirefoxDriver(ffprofile);
That way, Firefox will always start that profile. In the profile you do all the settings you need
You can assign to each Selenium grid 2 node a specific firefox profile:
java -jar selenium-server-standalone-2.37.0.jar
-Dwebdriver.firefox.profile=my-profile -role node -hub http://example-server.org:4444/grid/register
Notice that the value of the webdriver.firefox.profile has to be the firefox profile name, not the location or the folder name
When running webdriver on a test server with no options to create profiles on the machine you can create your profile programmatically:
private FirefoxProfile GetFirefoxProfile()
{
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("network.automatic-ntlm-auth.trusted-uris", "http://localhost");
return firefoxProfile;
}
Fetching a profile is not useful as it is internally creating another copy of the fetched named profile. Accessing the original profile is required if
for eg: test coverage data should be written to a data store across multiple invocations.
Here is a possible solution by Overriding the ProfilesIni class of Selenium
Start by creating a Custom profile using firefox -p, say "CustomSeleniumProfile"
ProfilesIni profileini = new ProfilesIni() {
#Override
public FirefoxProfile getProfile(String profileName) {
File appData = locateAppDataDirectory(Platform.getCurrent());
Map<String, File> profiles = readProfiles(appData);
File profileDir = profiles.get(profileName);
if (profileDir == null)
return null;
return new FirefoxProfile(profileDir);
}
};
FirefoxProfile profile = profileini.getProfile("CustomSeleniumProfile");
//profile.setEnableNativeEvents(false);
driver = new FirefoxDriver(profile);
//ffDriver.manage().deleteAllCookies();
driver.get("http://www.google.com");

Access to file download dialog in Firefox

Is there any kind of API that can allow me to manipulate a file download dialog in Firefox?
(I want to access the one that appears when user does something, not initiate one myself).
What I want to do is to access this dialog from Selenium (and whether Selenium "privileged mode" is enough to access chrome interface is something I am not sure about as well).
I have a solution for this issue, check the code:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to("http://www.myfile.com/hey.csv");
I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.
Of course this was Java, I've translated it to Python:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")
browser = webdriver.Firefox(firefox_profile=fp)
In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf
Not that I know of. But you can configure Firefox to automatically start the download and save the file in a specific place. Your test could then check that the file actually arrived.
Web Applications generate 3 different types of pop-ups; namely,
1| JavaScript PopUps
2| Browser PopUps
3| Native OS PopUps [e.g., Windows Popup like Upload/Download]
In General, the JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle these JavaScript pop-ups, such as Alert.
Eventually, the simplest way to ignore Browser pop-up and download files is done by making use of Browser profiles; There are couple of ways to do this:
Manually involve changes on browser properties (or)
Customize browser properties using profile setPreference
Method1
Before you start working with pop-ups on Browser profiles, make sure that the Download options are set default to Save File.
(Open Firefox) Tools > Options > Applications
Method2
Make use of the below snippet and do edits whenever necessary.
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\\Test\\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
driver = new FirefoxDriver(profile);
Most browsers (in mine case Firefox) select the OK button by default. So I managed to solve this by using the following code. It basically presses enter for you and the file is downloaded.
Robot robot = new Robot();
// A short pause, just to be sure that OK is selected
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
I was facing the same issue.
In our application the instance of FireFox was created by passing the DesiredCapabilities as follows
driver = new FirefoxDriver(capabilities);
Based on the suggestions by others, I did my changes as
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/octet-stream");
driver = new FirefoxDrvier(firefoxProfile);
This served the purpose but unfortunately my other automation tests started failing. And the reason was, I have removed the capabilities which were being passed earlier.
Some more browsing on net and found an alternate way. We can set the profile itself in the desired Capabilities.
So the new working code looks like
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// add more capabilities as per your need.
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/octet-stream");
// set the firefoxprofile as a capability
capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);
driver = new FirefoxDriver(capabilities);
Dont know, but you could perhaps check the source of one of the Firefox download addons.
Here is the source for one that I use Download Statusbar.
I had the same problem, I wanted no access of Save Dialogue.
Below code can help:
FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.download.folderList",2);
fp.setPreference("browser.download.manager.showWhenStarting",false);
fp.setPreference("browser.helperApps.alwaysAsk.force", false);
// Below you have to set the content-type of downloading file(I have set simple CSV file)
fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
According to the file type which is being downloaded, You need to specify content types.
You can specify multiple content-types separated with ' ; '
e.g:
fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");
Instead of triggering the native file-download dialog like so:
By DOWNLOAD_ANCHOR = By.partialLinkText("download");
driver.findElement(DOWNLOAD_ANCHOR).click();
I usually do this instead, to bypass the native File Download dialog. This way it works on ALL browsers:
String downloadURL = driver.findElement(DOWNLOAD_ANCHOR).getAttribute("href");
File downloadedFile = getFileFromURL(downloadURL);
This just requires that you implement method getFileFromURL that uses Apache HttpClient to download a file and return a File reference to you.
Similarly, if you happen to be using Selenide, it works the same way using the built-in download() function for handling file downloads.
I didnt unserstood your objective,
Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.
In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.
In addition you can add
profile.setPreference("browser.download.panel.shown",false);
To remove the downloaded file list that gets shown by default and covers up part of the web page.
My total settings are:
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.merge(capabillities);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setPreference("browser.download.folderList", 4);
profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.panel.shown",false);
dc.setCapability(FirefoxDriver.PROFILE, profile);
this.driver = new FirefoxDriver(dc);

Resources