Saving a screenshot in a custom directory using Javascript Selenium

Is it possible to save a screenshot in a custom directory instead of the default root folder? Thank you

Answer №1

When using fs.writeFileSync(), you have the ability to specify the location where a file should be saved.

For instance, what you are currently doing can be written as:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('./Customer_Card.png', data, 'base64')
})

If you need to save your file in a different location, simply include the path.

Saving into a sub-directory

const path = require('path');

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync(path.join(__dirname, 'innerDir', 'Customer_Card.png'), data, 'base64')
})

The code above will save your file as Customer_Card.png inside the innderDir directory (located at the same place as the current file).

For example, consider this project structure:

+ MyProjectDir
+---+ savePhoto.js
+---+ innerDir

After running the code, the structure would be:

+ MyProjectDir
+---+ savePhoto.js
+---+ innerDir
+---+---+Customer_Card.png

__dirname is an environment variable that provides the absolute path of the directory containing the executing file.

You can also use a relative path like this:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('./innerDir/Customer_Card.png', data, 'base64')
})

Saving in a parent directory

To move up a directory instead of going into a directory, use this approach:

driver.takeScreenshot().then(function(data) {
    fs.writeFileSync('../Customer_Card.png', data, 'base64')
})

For clarification, if your project layout was like:

+ MyProjectDir
+---+ innerDir
+---+---+ savePhoto.js

Running the above code (from savePhoto.js) would result in:

+ MyProjectDir
+---+ Customer_Card.png
+---+ innerDir
+---+---+ savePhoto.js

This concept can be expanded to save files at various levels such as

./innerDir/innerDir2/Customer_Card.png
, ../../../Customer_Card.png, or ../../innerDir/Customer_Card.png.

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

React modal image showing a misaligned image upon clicking

I recently integrated the react-modal-image library into my project to display images in a modal when clicked. However, I encountered an issue where the displayed image is off center with most of it appearing offscreen. I'm unsure what is causing this ...

JavaScript functions are experiencing issues when used within the document.ready() function

I am facing an issue where adding a second function in JavaScript causes it to stop working on my page. Could someone help me identify the possible error? Your assistance would be greatly appreciated. It's worth noting that when I comment out the sec ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

Tips for sending multiple values as a unified object using Javascript and Ajax

Currently, I am new to javascript and MVC. I am developing a sample application with a sign-up page where I am using ajax for the process. The code snippet below shows my current implementation: function create() { var user_name = $("#txtUser").val(); ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Looking to retrieve specific user information by clicking a button within Angular 4?

I'm working on a table that includes a button to access specific user details. https://i.sstatic.net/NzXWj.png Currently, I am retrieving data as follows: in html: <tr *ngFor="let userData of user?.users; trackBy: userThumb"> ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...

Can the typical drag and drop cursors be ignored in an HTML drag operation?

I've been working with the HTML drag and drop API to allow users to resize columns in a table. However, I've noticed that when a user starts dragging a column, the cursor changes to one of the default drag and drop effects (such as move or none). ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Turn off Chrome Autofill feature when placeholders are being used in forms

I am encountering difficulties with Google autofill for fields that have placeholders. Despite attempting various solutions provided at: Disabling Chrome Autofill, none of them seem to work as needed. The challenge is to create a form with different field ...

A guide to choosing an option from a dropdown menu based on a specific text pattern using Selenium WebDriver and Java

Is there a way to select an option from a dropdown list based on only part of the visible text? The complete text may not always be consistent. Any assistance with this would be greatly appreciated. ...

Obtain the updated cart total for WooCommerce when the 'updated_cart_totals' jQuery event is triggered

Currently, I have implemented the updated_cart_totals jQuery event to monitor updates to my WooCommerce cart. While this setup successfully triggers when the cart is updated, I am also seeking a way to retrieve the updated total for the cart. Below is the ...

Display an image when the link is hovered over within a table

I'm looking for a way to display a scanned receipt image when hovering over a link within a table. I've written some code but it's not working as expected. Can anyone help me figure out what's wrong? Here is the current state of my cod ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

Top Strategies for PHP - Managing Directs and Header Content

PHP is a versatile language frequently used for generating 'templates' like headers to maintain a consistent look across websites and simplify updates via require or include commands. Another common task involves managing log-ins and redirecting ...

SailsJs: Model.find().exec() can sometimes generate unexpected properties

I recently created a service function in api/services/SomeServices.js getCreditDebitNotes:function(vid){ console.log('resolving credit and debits'); var deferred=sails.q.defer(); CreditDebitNotes.find({vendorID:vid,status:1},{selec ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

Is it possible to halt code execution in Node JS after sending a response?

I am currently learning Node JS and practicing to develop a MERN app. I have implemented two middleware functions named getUserById and isSignedIn. router.param("userId",getUserById) const getUserById = (req,res,next,id)=>{ User.findById( ...

Tips for retrieving the newly created instance in Sequelize

I have been experimenting with sequelize for my new project, but I am facing difficulties in returning the created instance. Any help would be appreciated. Below is my create method : exports.create = (req, res) => { let user = { "user ...