Guide on launching a Firefox browser through Selenium 3.6.0 with a different profile in JavaScript

How can I customize the Firefox browser settings in selenium-webdriver 3.6.0 for automated testing? I need Firefox to download files without prompting and save them to a specific directory.

For Google Chrome, the approach is as follows:

if (this.bName === 'chrome') {  
   var cap = Capabilities.chrome();  
   var options = {  
      'prefs': {  
          profile: {  
            default_content_settings: {  
                  popups: 0,  
            },  
          },  
          download: {  
            default_directory: path.join(__dirname,  
 '/../Downloads For Testing'),  
          }  
      }  
 };  
 var cap = cap.set('chromeOptions', options);  
 this.browser = new Builder().withCapabilities(cap).build();  
}

However, trying the same method with Firefox by creating a new profile did not work.

I imported the Profile from the Firefox folder

firefoxProfile = require('selenium-webdriver/firefox').Profile;

and set up new capabilities like this:

else if (this.bName === 'firefox') {
            var cap = Capabilities.firefox();
            var profile = new firefoxProfile;
            profile.setPreference("browser.download.folderList", 2);
            profile.setPreference("browser.download.manager.showWhenStarting", false);
            profile.setPreference("browser.download.dir", path.join(__dirname, '/../Downloads For Testing'));
            profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/html");
            cap.set('firefox_profile', profile);
            console.log(profile);
            this.browser = new Builder().withCapabilities(cap).build();
        }

The created profile object looks like this:

Profile {
  preferences_:
   { 'browser.download.folderList': 2,
     'browser.download.manager.showWhenStarting': false,
     'browser.download.dir': 'C:\\path\\Downloads For Testing',
     'browser.helperApps.neverAsk.saveToDisk': 'text/html' },
  template_: undefined,
  extensions_: []
}

While there are no errors during initialization and all promises are returned correctly by Mocha, the test framework, the prompt dialog still appears when trying to download a file on Firefox.

Answer №1

The index.js file in selenium-webdriver\firefox provides clear instructions on how to dynamically create a new profile and set preferences within the browser.

* The {@linkplain Profile} class allows for configuration of the browser profile
* that is used with WebDriver. This includes functions to add additional
* {@linkplain Profile#addExtension extensions}, customize browser
* {@linkplain Profile#setPreference preferences}, and more. For instance, you
* might want to integrate Firebug:
*
*     const {Builder} = require('selenium-webdriver');
*     const firefox = require('selenium-webdriver/firefox');
*
*     let profile = new firefox.Profile();
*     profile.addExtension('/path/to/firebug.xpi');
*     profile.setPreference('extensions.firebug.showChromeErrors', true);
*
*     let options = new firefox.Options().setProfile(profile); 
*     let driver = new Builder()
*         .forBrowser('firefox')
*         .setFirefoxOptions(options)
*         .build();

I attempted the method but encountered issues. While I didn't try adding an extension, setting the 4 preferences mentioned in my question did not yield desired results.

To work around this, I found success in creating a new profile by running firefox.exe -p via the Windows Run dialog. (Press the Windows icon key and R on your keyboard to access the run dialog)
Subsequently, I used this "testing" profile as a blueprint to dynamically generate a new temporary profile through selenium.

var profile = new firefox.Profile('/pathTo/firefox profile for testing/');

An important aspect to consider involved Firefox's handling of MIME types. Discrepancies between the server-sent content-type and Firefox's identification may lead to download prompting instead of automatic saving.
This behavior likely serves security purposes.
Additional information on content types can be found here

In my scenario regarding a CSV file, setting

profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv")
while the server sent a text/html content-type, causing Firefox to perceive it as a TXT file, was ineffective.
Thus, I adjusted the handlers.json file within
/pathTo/firefox profile for testing/
by modifying the 'ask' attribute under 'mimeTypes' from true to false for 'text/plain' entries.

Additionally, I configured the download directory path as the sole preference. This action also facilitated folder creation, at least for the final directory. My implementation looked like:

    else if (this.bName === 'firefox') {
        var cap = Capabilities.firefox();
        var profile = new firefox.Profile('/pathTo/firefox profile for testing/');
        profile.setPreference("browser.download.dir", '/pathTo/Downloads For Testing');
        let options = new firefox.Options().setProfile(profile);
        this.browser = new Builder().forBrowser(this.bName).setFirefoxOptions(options).build();
    }

Another suggested approach involves modification of handler.json, although I did not find success using this method.

Alternatively, brute force methods have been proposed, yet these were unsuccessful in my case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Creating a dynamically changing AppBar component in material-ui-next React that responds to scroll events

Following the Material Design guidelines, the top app bar should exhibit specific behavior: When scrolling, the top app bar can [...] undergo the following changes: - Scrolling upwards hides the top app bar - Scrolling downwards reveals the top ...

Having trouble establishing a connection with Firefox

Currently utilizing Selenium, I have a hub connected to two Linux virtual machines running various browsers. Initially, I was successfully able to launch browsers. However, suddenly the browser launching functionality stopped working. Firefox and other br ...

Looking for assistance on how to access a JSON file in JavaScript without the need for servers

As I embark on my journey with JavaScript, a question has been lingering in my mind - is it possible to access a JSON file locally, without the need for servers like WAMP? My goal is to simply retrieve the data from a JSON file and display its contents o ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

Connect the incoming http request information to a different controller

My navigation menu has the following structure: <div class="collapse navbar-collapse" id="admin-side-nav" ng-controller="AdminNav"> <ul class="nav nav-pills nav-stacked"> <li><a href="/admin/leaderboard/{{gameId}}">Lead ...

Sharing information in React applications

I'm a beginner when it comes to using javascript and React, so I have a question regarding posting data from within a component. In my scenario, I am utilizing the fetch API for making POST requests. Below is the code snippet I have created: export f ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Tips for saving images that are loaded indirectly on websites

Is there a way to save images that are loaded using methods other than being embedded directly in web pages or stored in a temp folder or browser cache? You can check out the situation I am referring to here. Any tips on saving images from the gallery on ...

Is there a way to modify the Javascript for this Contact Form to trigger a different action if a specific key is pressed instead?

I have been working on a Contact Form that integrates Google Scripts. Everything seems to be functioning well as it successfully sends emails and formats them properly in my inbox. However, there are two issues that I am encountering: -I want to exclude t ...

QUnit - looping through tests with consistent index values

Currently, I am in the process of testing some code and in order to do so, I am running multiple tests in a loop. Here is the code snippet I am using: for (var i = 1; i <= 5; i++) { QUnit.test('Hello ' + i, (assert) => { consol ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

Is there a way to retrieve the password of the currently logged in user using Keycloak in JavaScript?

Does anyone know how to access the password of a logged-in user in a React application using Keycloak? I have successfully retrieved most of the necessary information from the idToken, like this: keycloak.init({ onLoad: 'login-required'}).then(fu ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

What is the best way to disable the functions doajax_red and doajax_blue when a radio button is checked?

Is there a way to halt the functions doajax_red and doajax_blue when a radio button is checked? Upon loading the page index.php, clicking the red button will display a loading image. If you check the BLUE radio button and then re-check the RED radio butt ...

Display all elements with a blank attribute using jQuery

I'm currently dealing with a list containing multiple hidden list items: <ul> <li rel=""> </li> ... </ul> My goal is to display only those list items that have an empty string as the value of the attribute rel. D ...

What's the source of this undefined error and is there a way to eliminate it from the code?

After successfully filtering and reducing the data, I encountered an issue with undefined. I am trying to figure out what is causing this and how I can either remove it or make it visible on the screen without being invisible. You can also check the codes ...

What is the mechanism behind the operation of the inherits feature in Node.js?

The following code snippet illustrates how the inherits function works in node.js: exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

Having trouble updating state with useEffect in a React functional component

Currently, I am dealing with a React functional component that is calling an API to fetch data. The response from the API call is confirmed to be received successfully. My aim is to store this data in an array within the component's state so that it c ...