1

Am working on an application which has a link to download a file. Am trying to create a functionality using Javascript whereby I want to detect immediately the file has been downloaded then perform some extra task. I have tested by downloading a file but it doesnt throw the alert box.

Anchor link to be clicked

<a href="{{ route('b2c.policy') }}" id="policyDownload" target="_blank"> Download Policy Document</a>

Logic to detect downloads

$( "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
  • Googling the exact title of your question .... https://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download – Seba99 Feb 22 '19 at 10:38
  • @Seba99 I want to detect download only on client side – Martin Feb 22 '19 at 10:49

0 Answers0