0

Am working on a challenging task whereby I have an application which has a link which when clicked a document should be downloaded. I have written some Javascript code to detect immediately the browser receives a download I should perform some action. My code seems not to detect any file received on download.

I have tested by downloading a file but it doesnt throw the alert message.

Anchor link to be clicked

<a href="{{ route('b2c.policy') }}"
   download="Monthly Report for March 2014.pdf" id="policyDownload">Download Policy</a>

Javascript code to detect download

$( "a#policyDownload" ).mousedown(
    function(e) {
      //Get current time
      var downloadID = ( new Date() ).getTime();

      // Update the URL that is *currently being requested
      $( "a#policyDownload" ).href += ( "?downloadID=" + downloadID );

      //search for the name-value pattern with the above ID.
      var cookiePattern = new RegExp( ( "downloadID=" + downloadID ), "i" );

      //watch the local Cookies to see when the download ID has been updated by the response headers.
      var cookieTimer = setInterval( checkCookies, 500 );

      //check the local cookies for an update.
      function checkCookies() {
          // If the local cookies have been updated
          if ( document.cookie.search( cookiePattern ) >= 0 ) {
              clearInterval( cookieTimer );
              alert('Downloaded');
          }
      }
    }
  );
Martin
  • 547
  • 2
  • 11
  • 40
  • Why would a cookie update after downloading something? –  Feb 27 '19 at 07:50
  • @psinaught Just some code was trying out but didnt work,, whats your opinion .. – Martin Feb 27 '19 at 08:03
  • Have you set the cookie from server? Here it uses similar approach - https://stackoverflow.com/a/4168965 –  Feb 27 '19 at 08:07
  • I would like to know about use case of catching the download. Usually user decides what happens with downloaded file. –  Feb 27 '19 at 08:13
  • @psinaught I was offline ,, I want to achieve a functionality whereby if the user has downloaded the file I want to show him some success message and redirect him/her to another page.. – Martin Feb 27 '19 at 09:36

0 Answers0