The download of the blob contained within an iframe could not be completed

Here is the code snippet that I've written to set the src attribute of an iframe to a blob URL:

function initiateDownloadFromIframe(fileData: any) {
  const iframe = document.createElement('iframe');
  iframe.setAttribute('style', 'display: none;');
  const newBlobUrl = window.URL.createObjectURL(new Blob([fileData.blob], {type: 'application/pdf'}));
  iframe.setAttribute('src', newBlobUrl);
  const checkForDownload = () => {
    if (iframe.contentWindow) {
      setTimeout(function() {
        // Remove iframe after 1 minute, assuming download has started
        iframe.parentNode!.removeChild(iframe);
      }, 60000);
    } else {
      setTimeout(checkForDownload, 100);
    }
  };
  checkForDownload();
  document.body.appendChild(iframe);
}

I want the iframe to automatically trigger the download of the PDF contained in the blob. However, at present nothing happens when this function is called.

Answer №1

If you're looking to "download" and save on disk, the easiest way is by using an HTMLAnchorElement with its download attribute.

To cover all edge cases, including old IE and Safari quirks, you can utilize the lightweight FileSaver script.

var blob = new Blob(["I'm just a text file..."], {type: 'plain/text'});
saveAs(blob, 'myFile.txt');
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.js"></script>

Keep in mind that the iframe hack solution should only be considered as a last resort, as it is not the most effective method.

Another important point to note is that browsers are capable of displaying PDF files directly, which may prevent the automatic download action.

<iframe src="https://cdn.jsdelivr.net/gh/mozilla/pdf.js/test/pdfs/S2.pdf"></iframe>

(Please be aware that there may be issues with certain Chrome versions when dealing with nested iframes and PDF viewers. Here is a link to a live example on Plunker for further testing in this browser.)

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

Performing repeated insertion using a foreach loop

I am seeking a way to add multiple rows into a database table. This is the HTML code: <tr> <td style="display:none"><input type="text" rows="4" name="teste[]" value="<?php echo $produto8["Id"]; ?>"></td> <td><textar ...

What is the best way to modify the background of my li element when it is clicked on?

I stumbled upon this article: Modifying Li Element Colors in HTML <ul> Using onclick Event It seems to address what I need, but I'm a little unsure of how to implement something similar in a rails app that also utilizes react/redux. Most of the ...

Accessing range slider values in a separate function with Javascript

In my project, I have a range slider that provides minimum and maximum mileage values. I need to access these values in another Javascript function for additional processing. Everything was working fine until I attempted to encapsulate the slider within a ...

Creating a subclass of `Error` leads to the error message "only refers to a type, but is being used as a value here."

I currently have Typescript 4.0.2 installed. Within lib.es5.d.ts, there is the snippet provided below: interface Error { name: string; message: string; stack?: string; } interface ErrorConstructor { new(message?: string): Error; (messa ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

Implementing AngularJS to display different divs according to the selected value

I am attempting to utilize the value of an HTML select element to toggle the visibility of specific div tags using AngularJS. Below is the code snippet I have been working with: <body ng-app="kiosk" id="ng-app" > <div class="page" ng-controll ...

How can I adjust the top margin of a legend that is placed at the bottom of a Doughnut chartjs graph?

I've been working on customizing doughnut graphs with ChartJS and I'm struggling to create space between the graph and the legend. Here's my legend configuration: plugins: { legend: { display: true, align: 'start', p ...

Issue with Angular-material Date-Picker functionality

Seeking assistance with why the angular-material date-picker is not functioning. The code in my cshtml file looks like this: <label>Date and time</label> <md-content> <md-datepicker ng-model="viewModel.employee.contractE ...

Is there a way to identify when an image extends beyond the boundaries of the browser window and subsequently reposition it?

Currently, I am implementing a method found at this link to display popup images of my thumbnails. However, there is an issue when the thumbnail is positioned close to the edge of the screen and the original image is too large, causing it to be cut off by ...

Struggling to fetch the JSON data for a specific field in NodeJS?

I am currently using NodeJS and MongoDB to make a GET request to an API endpoint. In my app.js file: app.get('/api/matches', (req, res) =>{ //console.log('Get matches..'); matches.find({}).then(eachOne => { res. ...

Exploring the ambiguity of explicit types with type generics

I am facing a type error issue with a Higher-Order Component (HOC): Error: Type 'number[]' is not assignable to type 'string'. Here is how I set up my HOC: const ComponentPage = renderPage(Component); However, I encounter the error ...

Summing up the values of elements with the same class in jQuery

<tr role="row" class="odd"> <td class=" stock-log-opening open ">0 PCS</td> <td class=" stock-log-opening"><i class="fa fa-rupee"></i> 0.00</td> <td class=" stock-log-opening"><i class="fa fa-rupe ...

Ways to assign scores to every response button

Below is an excerpt of code that showcases a list of potential answers for each question in the form of checkbox buttons. The task at hand is to assign marks to each answer button, which can be retrieved from the database. Marks for correct answers are obt ...

The initialization of the Vue.js Router component occurs just once, not every time the page is loaded

Every time I access this page, I have to include the "D3.js" script. Everything works fine the first time I visit the page, but if I navigate to another page and then return, the script doesn't seem to load properly. It appears that the "mounted" func ...

What is the best way to display the text of a button once it has been clicked?

Trying to implement a fade-in effect on text when clicking a button. Any assistance would be greatly appreciated! $(".btnClick").click(function(event) { var x = $(this).text(); if (x == "PowerApps") { $(this).parent(".show-details").find('. ...

Exploring Typescript's type narrowing capabilities through destructuring

This code snippet is encountering errors: type Example = { x: true, y: null, z: null } | { x: false, y: Error, z: null } | { x: false, y: null, z: { val: number} } function getExample(): Example { return { x: false, y: null, z: { val ...

Incorporating image attribution in JavaScript and HTML

As I delved into the world of JavaScript starting from scratch, my go-to resource was the w3schools website where code could be easily tested without any need for an IDE. Gradually, I transitioned to using Visual Studio 2010, expanding my knowledge along t ...

Employing ajax.actionlink in mvc4 results in a page refresh

I am working on a view that looks like this: @model IEnumerable<DomainClasses.Class> @{ ViewBag.Title = "لیست "; } <div id="test"> <h2>لیست کلاس ها</h2> <p> @Html.ActionLink("ایجاد کلاس جدی ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

What is the best way to monitor the elements within ngRepeat in AngularJS?

Hello everyone, I am facing a minor issue that I seem unable to resolve. I have a search input field that allows users to search through a table in all columns. However, I am struggling to track the items in ngRepeat effectively. Below is the search inpu ...