Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to trigger a callback after a window.location change is finished?

All of the following will successfully redirect a user to another page (with their own caveats, of course):

  • window.location.replace(new_url),
  • window.location.assign(new_url),
  • window.location = new_url,

The typical response to someone asking if you can get a callback for changing location is, of course, no, because whisking a user off to a new page means the scripts on your page are no longer active.

That's all fine and dandy, but in the case where you are using any of the three methods above to download a file, not only does the user stay on the same page as they are on, but there is also a slight lag (depending on network speeds) between updating location and when the file actually starts downloading.

In this situation (the user remaining on the page in which window.location was updated), is there any way to create a callback that would enable, for example, a loading icon being displayed the line prior to the redirect up until the file actually starts downloading?

like image 472
drusepth Avatar asked Aug 26 '14 19:08

drusepth


People also ask

What does window location replace do?

Window location. The replace() method replaces the current document with a new one.

What is callback() in js?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

What is the purpose of a callback function?

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." button.

What is callback html?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


1 Answers

You can create a hidden iFrame, pointing at the downloadable file. The user won't notice the difference, at the same time you can continue running scripts on the main document.

function downloadURL(url, callback){
   var hiddenIFrameID = 'hiddenDownloader' + count++;
   var iframe = document.createElement('iframe');
   iframe.id = hiddenIFrameID;
   iframe.style.display = 'none';
   document.body.appendChild(iframe);
   iframe.src = url;
   callback();
}
downloadURL("http:\\...", function() { alert('is downloading'); });
like image 160
Semyon Krotkih Avatar answered Oct 14 '22 04:10

Semyon Krotkih