views:

99

answers:

1

I'm using a the confirmit java script function to redirect to a new url with a positive response. It doesn't do exactly what I want - and maybe I can't have exactly what I want.

Here's what it does - onunload, with a positive response it opens the new url in a new window, which can be blocked by a pop-up blocker without the user even knowing, giving the impression that nothing happened. When it does open the new URL it opens in a new window making the desktop crowded. Its just not a great solution.

What I want it to do - onunload I'd like it to open the new url in the same window and have it not be classified as a "pop-up" to be blocked. I tried switching to onbeforeunload.... nuthin.

Is there a simple solution?

here's my current code:

<script language=javascript>
function confirmit() 
{ 
var closeit= confirm("My message"); 
if (closeit == true) 
{window.open("http://MyDestinationURL");} 
else 
{window.close();} } window.onunload = confirmit  
</script> 
A: 

Instead of opening a new window you can set the location of the current window:

<script type="text/javascript">

function confirmit()  { 
  if (window.confirm("My message")) {
    window.location.href = 'http://MyDestinationURL';
  } else {
    window.close();
  }
}

window.onunload = confirmit;

</script>

I am not sure if you actually want the else case where it tries to close the current window. If you just want to stay on the current page on a negative response, remove the else part.

Guffa
I tried using window.location.href = 'http://MyDestinationURL';and window.location = 'http://MyDestinationURL';Neither works. I'll get the confirmit message, but when I click "ok" it does not redirect to http://MyDestinationURL. I'm testing in Safari and Firefox. Any ideas?full, updated code:<script type="text/javascript">function confirmit() { if (window.confirm("My message")) {window.location.href = 'http://URL'; } }window.onunload = confirmit;</script>
Dan Peschio
@Dan: Aaaah. I just realised that it's from the `onunload` event that you try to do this. As the window is already destined to be closed, there is no point in setting a new location. Opening a new window is the only way of opening a new page at that stage. You have to use the `onbeforeunload` event if you want to be able to keep the window from closing.
Guffa
Still doesn't seem to work... heres the test page http://instantmediakit.poweredbytom.com<script type="text/javascript">function confirmit() { if (window.confirm("My message")) {window.location.href = 'http://newurl'; } }window.onbeforeunload = confirmit;</script>
Dan Peschio
@Dan: You have to return `false` from the event to stop it, otherwise it will just continune to close the window or navigate to the original destination.
Guffa