Cordova / Ionic - Download file from InAppBrowser

Ariel picture Ariel · Nov 24, 2015 · Viewed 13.7k times · Source

The scenario goes like this: I open a website in InAppBrowser, after the user ends with the work over there, the site generates a .pdf for the user to download, the problem is that the pdf does not download, it opens it in the browser.

Is there a way to make it download from the InAppBrowser? I'm currently working on an iOS app, so the solution would be better for iOS.

Thanks in advance.

Answer

Ariel picture Ariel · Dec 3, 2015

Following @jcesarmobile advices this is what I came up with:

First I had to install the cordova-plugin-file-transfer

Open URL

var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');

Create a listener on that windowref for a loadstart event and check if what's being loaded is a pdf (that's my case).

windowref.addEventListener('loadstart', function(e) {
  var url = e.url;
  var extension = url.substr(url.length - 4);
  if (extension == '.pdf') {
    var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
    var options = {};
    var args = {
      url: url,
      targetPath: targetPath,
      options: options
    };
    windowref.close(); // close window or you get exception
    document.addEventListener('deviceready', function () {
      setTimeout(function() {
        downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
      }, 1000);
    });
  }
});

Create the function that will handle the file download and then open it:

function downloadReceipt(args) {
  var fileTransfer = new FileTransfer();
  var uri = encodeURI(args.url);

  fileTransfer.download(
    uri, // file's uri
    args.targetPath, // where will be saved
    function(entry) {
      console.log("download complete: " + entry.toURL());
      window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
    },
    function(error) {
      console.log("download error source " + error.source);
      console.log("download error target " + error.target);
      console.log("upload error code" + error.code);
    },
    true,
    args.options
  );
}

The problem i'm facing now is the path where it downloads, I just can't open it. But well, at least file is now downloaded. I will have to create a localStorage item to save the paths for different files.

Many validations are missing in this steps, this was just an example I made quickly to check if it works. Further validations are needed.