What is the best way to download PDF files that are generated dynamically in a PWA when it is saved to the home screen on

My Progressive Web App allows users to generate a PDF report by clicking on a link. However, when the file opens, there is only an OK button to close it. This issue occurs when the user adds the app to their home screen:

I tried using a simple <a href> HTML tag, but even the OK button to close the file did not appear, forcing me to restart the app. When I used the JavaScript function window.open(), I was able to include an "OK" option to close the file.

<img src="pdf.png" onclick='generatePDF(1045, 45)'>
function generatePDF(c, v){var window=window.open("generatePdf.php?c="+c+"&v="+v, "pdf", "location: 0;");}

I want to provide users with options to print, share, or save that PDF file locally. When the app is used in a Safari Tab, these options are available.

UPDATE 16/07/2019 It seems like Safari is finally addressing the bug related to the

<a href="" download="name">
tag, as mentioned here: iOS: Add support for the download attribute. Soon, the download tag will work properly again.

Answer №1

Success on my end!


    function fetchAndSavePDF(pdfURL) { 
      var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfURL, true);
      xhr.responseType = 'blob';
      xhr.onload = function(event) {
        if (this.status == 200) {
          var pdfBlob = this.response;
          var downloadLink = document.createElement('a');
          downloadLink.href = window.URL.createObjectURL(pdfBlob);
          downloadLink.download = "yourfile.pdf";
          downloadLink.click();
        }
      };
      xhr.send();
    }

Answer №2

When a PWA is added to the home screen, it will display according to the settings chosen in the display property of the web app manifest (for more details, check out this article). However, essentially it functions just like a regular web application.

So if you want to include HTML elements for user interaction on the page, you will need to add them yourself. You could consider implementing a custom menu or header bar, for example.


Update

In general, when opening external links within a PWA, it is recommended for better user experience to open them in the browser rather than within the PWA itself. Users typically prefer to stay within the context of the PWA. If you choose to open a PDF in a separate browser page that is not part of your app, you won't be able to add additional buttons beyond what the default browser provides.

One suggestion is to try opening the PDF within a div/container inside your PWA using different libraries available, and then customize any UI elements you require.

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

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Error in JSON Format Detected in Google Chrome Extension

Struggling with formatting the manifest for a simple Chrome extension I'm developing. I've been bouncing back and forth between these two resources to try and nail down the correct syntax: https://www.sitepoint.com/create-chrome-extension-10-mi ...

What is the best way to keep my bottom navigation bar attached to my top navigation bar?

I am facing an issue with my two navbars. The top navbar sticks to the top of the page when the user scrolls down, which works perfectly fine. However, when the user logs in, the bottom navbar becomes visible. Unfortunately, the bottom navbar is not sticky ...

There was a hiccup in the camera positioning as the tweening began

I've been working on a basic program that involves tweening the camera to a specific position. The functionality works smoothly for the most part, however, I encounter some glitches at the start of the transition when trying to pan the camera using or ...

Utilizing Sails.js: Invoking a YouTube service through a controller

I am facing an issue while trying to integrate Youtube Data API with Node.js in Sails.js. The problem lies with the "fs.readFile" function. Upon launching the service, it returns "undefined". Below is the code snippet for YoutubeService : module.exports ...

How can I store a value or text to track view counts or a counter efficiently?

Recently, I've been trying to implement a view counter on my website, similar to what you see on YouTube. Currently, the number of views stands at 23. I managed to find some code that allows me to increment the view count every time I click on an imag ...

Is there a way to make sure that my submit button aligns perfectly with the text beneath it

I am new to coding and I need help aligning my submit button with the text "You can contact Armando through his freelance portfolio on Upwork by clicking...". Can anyone assist me with this? .topnav { background-color: #333; overflow: hidden; } .to ...

Warning: The res.sendfile method is now deprecated. Please use res.sendFile instead

I am currently using res.sendfile(..) in my router/index.js like this: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.sendfile('public/app.html&a ...

What is the process for determining form field values in both directions?

My goal is to create an item form that allows me to input various formulas to calculate specific fields. Main Concern: I want the formulas to work in both directions, for instance When a user enters the price of an item, the form should automatically ca ...

Why does my Angular service throw an error stating "undefined is not a function" when passing my function as an argument?

I am currently working on implementing factory and two constructor patterns in Angular. My goal is to convert the factory into an Angular service. Below is a simplified version of the code I am working with: function processFactory () { // some code ...

What could be causing the consistent Mocha "timeout error" I keep encountering? Additionally, why does Node keep prompting me to resolve my promise?

I'm encountering a timeout error repeatedly, even though I have called done(). const mocha = require('mocha'); const assert = require('assert'); const Student = require('../models/student.js'); describe('CRUD Tes ...

Tips for effectively handling numerous events from multiple Slickgrid instances on a single page

I'm encountering an issue with utilizing multiple Slickgrids on a single page. With the number of grids changing dynamically, I generate them within a JavaScript function and maintain them in a grid array as shown below. var columns = []; var options ...

Troubleshooting problem with Bootstrap Accordion & Silverstripe caused by Button class toggle bug

For a Silverstripe project, I am utilizing Bootstrap's accordion feature. The markup closely resembles Bootstrap's documentation but with slight modifications: aria-expanded="false" and panel-collapsed lack the in class to keep all items closed b ...

Converting XML data (in SOAP format) to a JSON object using JavaScript

Can AJAX be used to send cross-site requests with a SOAP request and receive an XML response? Additionally, is there a framework similar to Mustache that can easily convert the XML response to JSON format? ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Is it necessary for IDs to be unique within the React DOM?

I am new to React and curious if the same rules that apply to regular DOM also apply to React DOM, particularly regarding the uniqueness of HTML element IDs. I'm concerned because in the codebase I'm currently working on, there's a checkbox ...

Quick guide on establishing a remote websocket connection to a Node.js server hosted on Heroku

I am facing issues while trying to establish a connection with a nodejs server using a websocket. Despite my efforts, I have not been successful. The server.js file in question appears as follows: var app = require('express')(); var http = req ...

``It appears that the reader.onload function is behaving unexpectedly on Android

I've been troubleshooting a bug in my project that works on iOS and desktop browsers but fails silently on android. I suspect the issue might have something to do with my FileReader. Any insights or advice would be greatly appreciated! function hand ...

I need help creating a Google marker using the Maps JavaScript API

I am currently working with the Google Maps API. The map displays the latitude and longitude when a mouse click event occurs. My next step is to add a Google marker to the map. Below is my JavaScript code snippet: <script> function initMap() ...

How to dynamically add multiple classes in Vue.js

I want to add multiple classes when the user clicks on an item. Currently, I have this code snippet: <div :class="[ item === form.score ? 'text-black bg-white': '' ]" @click="form.score = item" v-for="item in 10"> {{ i ...