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?
Window location. The replace() method replaces the current document with a new one.
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.
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.
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.
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With