0

I'm using the following meta header in order to download a file when a page is opened:

<meta http-equiv="refresh" content="3;URL=SomeFileName" />

Is there a way to make some javascript code run when the 3 seconds pass, i.e. just before the browser starts downloading SomeFileName?

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141

2 Answers2

1

You can use setTimeout() to time it but as stated in the comments it's a much better to redirect with JavaScript in this case. Example:

setTimeout(function(){
    /*
     * code here will be executed before the download
     */
    document.location = "downloadurl";
}, 3000); // 3000ms = 3s
Karl Laurentius Roos
  • 4,360
  • 1
  • 33
  • 42
  • Note that some user agents won't execute JS. Depending on requirements, it might be desirable to keep meta refresh header and remove it with JS (if browser is capable to do that) immediately on page load. – skalee Dec 16 '12 at 15:21
1

While a pure javascript redirect function would be a better solution most of the time, there might be times that you need it.

Take a look at these:
http://www.w3schools.com/jsref/event_onunload.asp
Alerts when navigating away from a web page
http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx
https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

Basically, an event is fired when the user tries to close or navigate away from the page. You can hook up to that event for customization.

window.onbeforeunload = function () {
  var who = ["lover", "friend"][(Math.floor(Math.random()*2)+1)];
  return "Goodbye my " + who;
};

This function is supposed to return a string or nothing. If it is a string, a dialog box appears for confirmation of navigating away; if it is nothing, i.e. undefined, no interception happens.

Also n ote that:

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.

Community
  • 1
  • 1
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96