Backing up PDF files via protractor

When I try to save a PDF file, I run into an issue. After clicking the Print button on my page, it redirects me to a new page with the PDF displayed in a standard Chrome PDF viewer. While this is convenient for users, I am unable to find a way to download the PDF because all I can see in the HTML code is:

<body style="background-color: rgb(38,38,38); height: 100%; width: 100%; overflow: hidden; margin: 0">
     <embed width="100%" height="100%" name="plugin" id="plugin" src="blob:https://myPage.com/e8aa96bf-5a46-4f74-8df6-424881a8774a" type="application/pdf" internalinstanceid="34" title="">
</body>

Does anyone know how to download a PDF in Protractor?

Answer №1

To save a PDF file, we can utilize the HTML 5 attribute called download. By creating an a element, clicking on it will initiate the saving process for the PDF.

The key is to construct our own

<a download="ourfile.pdf" href="blob:ourPath">
where download represents the desired file name and href points to the URL of the PDF or the src attribute in embed.

This element creation can be achieved by using browser.driver.executeScript();. Here's an example:

browser.getAllWindowHandles().then(function (handles) {
    browser.switchTo().window(handles[1]).then(function () {
        browser.ignoreSynchronization = true;
        browser.driver.executeScript(`var a = document.createElement('a');
                                      a.href = arguments[0];
                                      a.id="downloadPdf";
                                      a.download = "abc.pdf";
                                      a.text="DOWNLOAD"
                                      a.style="width:200px;height:200px;"
                                      var b = document.getElementsByTagName('body')[0];
                                      b.insertBefore(a, b.firstChild);
                                      `,
            browser.driver.getCurrentUrl()).then(() => {
                browser.driver.findElement(by.id('downloadPdf')).click();
                browser.ignoreSynchronization = false;
            });
    });
});

We provide the url as the second argument and insert our newly created element at the beginning of the body. Subsequently, we locate this new element and trigger a click event on it.

Additionally, we can define the path for saving our files by specifying the default_directory within the configuration file:

  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      prefs: {
            'download': {
                'prompt_for_download': false,
                'default_directory': 'C:\\your\\custom\\path\\',
            }
        }
    },
  }

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

Implementing a Pagination Component in React JS using Ant Design to Display 4 Products on Each Page

Is there a way to display 4 products on every page using the ant design Pagination component in React JS? My goal is to have 4 products shown on each page using the ant design pagination while also incorporating search and filtering functionalities. Curre ...

There is no way to avoid a PHP variable being displayed in a JavaScript alert box

It may sound silly, but I've spent hours trying to escape this PHP variable that contains post data: $post=array ( 'offers' => '90', 'pn' => '2', 'ord' => 'price', 'category_s ...

Is there a way to customize event property setters such as event.pageX in JavaScript?

Is there a way to bypass event.pageX and event.pageY for all events? This is because IE10+ has a known bug where it sometimes returns floating point positions instead of integers for pageX/Y. ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

Utilizing jQuery to Maintain State Across Page Refreshes with Cookies

Currently, I am attempting to create a script that can retain its state even after the page is refreshed. Here is my progress so far: Utilizing jQuery: $(window).ready(function() { var voteId = $('.gallery-item a'); $(voteId).click(function() ...

Employing the identical directive within a directive [angularjs]

My requirement is to utilize the same directive within another directive, based on a conditional parameter. However, every time I attempt to do this, it appears to enter an infinite loop. It seems like the templates are being preloaded and causing a recurs ...

Is there a method available to incorporate a scroller into an nvd3 chart?

I am encountering an issue with my nvd3 chart. When I have a large amount of data that exceeds the width of the chart container, there is no scroll bar present and I'm struggling to figure out how to add one. I attempted to include overflow:scroll wi ...

Rearrange Firebase data on the client side

Having trouble sorting data in Firebase for a web project. I tried using orderByChild to filter the data, but now I need to also order it by date. Here's what I've attempted: Tried using object.values with .sort, no luck Attempted to use lodas ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

Tips for refreshing the page using NavLink from React-Router?

Is there a way to use NavLink to highlight buttons with an active link and still load the page like an anchor tag? ...

Emphasize specific lines within a textarea

I am facing a challenge with a textarea dedicated to validating telephone numbers. My goal is to highlight the lines that contain invalid telephone numbers by adding two asterisks in front of them. However, I'm struggling to figure out how to highlig ...

Tips for managing and showcasing various user inputs in an array using JavaScript

I have been tasked with storing multiple user input values in a JavaScript array using the push method. Below is the code: <body> <h3>employee form</h3> <div class="row"> <div class="col-md-6" ...

Is there a way to view 2D flat items in 3D using either babylonjs or threejs?

I am currently utilizing fabricJS and have created a variety of random drawings (such as circles, squares, and polygon shapes) on a canvas shaped like a rectangle object (Base). My goal is to display all these drawings engraved on the main rectangle objec ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Tips for using jQuery dropdown menus

I am currently in the process of creating a prototype for a quick dropdown menu using jQuery. However, I have reached the limits of my knowledge on jQuery and could use some assistance in solving my issue. My objective is to have a dropdown animate down w ...

The Tiny Scrollbar jQuery plugin experiences a malfunction when the defer attribute is added to the script tags in the javascript code

After successfully setting up the jQuery plugin, Tiny Scrollbar, I encountered an issue when I attempted to defer the loading of the necessary javascript files. Here is an example of the code snippet: <script type="text/javascript" src="https://ajax.g ...

Examining Angular Modules using Jasmine Unit Tests

Currently, I am integrating an AngularJS service into my application. Upon testing, I discovered that the service is not as reliable as I had hoped. To address this issue, I decided to implement some unit tests for it. While the service functions properly ...

Performing a NodeJS MySQL query using chain promises

I have a set of 3 functions that I need to call step by step. For example, after calling the first function and getting a result, I must then call the second function and pass the parameter returned from the first call. Once the second call is completed, I ...