DhruvPathak
DhruvPathak

Reputation: 43265

Is this a good code to redirect parent window to a URL instead of the popup and close the popup?

This is the sample code:

  1. in the pop up :

    <body onunload='stopThisAndChangeParentInstead()' >
    
    <a href='MY_URL'> Click here </a>
    

When the user clicks "Click here", the unload event fires which changes the URL of the parent and closes this popup window.

function stopThisAndChangeParentInstead()
{
    window.opener.top.location.href = "MY_URL";
    window.close();

}

My questions:

  1. What are disadvantages of using this method?
  2. Are there any better ways to do the same thing?
  3. Is there a JavaScript way to know to which URL the page is being redirected to? So that I can use that in body unload function, instead of mentioning MY_URL since I already know it.

Upvotes: 0

Views: 4039

Answers (3)

Martin Jespersen
Martin Jespersen

Reputation: 26183

I'd suggest using the target attribute on the link inside the popup to make the url open in the parent window (target="_parent" or target="_top" ought to work) and then use javascript only for closing the popup. it's a cleaner solution in my opinion.

Upvotes: 3

Simeon
Simeon

Reputation: 5579

  1. The whole thing is a quite questionable way of creating a good user experience.
  2. There are always better ways of doing one thing, you could write more beautiful code or write a smarter solution to the same problem. But in this matter, I think you should look at another user experience instead of coding the same experience in another way. Put the user first! Is it clear that the parent window is going to redirect? Ask these questions to a user that is not too keen on using computers, and the results might surprise you.
  3. Yes, you can fetch the URL by doing:

.

<a id="myLink" href="http://myurl">
...
function stopThisAndChangeParentInstead()
{
    var url = document.getElementById('myLink').href;
    window.opener.top.location.href = url;
    window.close();
}

Upvotes: 1

schellmax
schellmax

Reputation: 6094

instead of using an unload event, i'd recommend attaching an onclick event to the anchor tags directly. using jquery this would be:

$('a').click(function(){
    window.opener.top.location.href = $(this).attr('href');
    window.close();
    return false; 
});

although it's a somewhat, say, unusual way to set up navigation this way, i can't see any problems arising from this (aside from confusing the user, maybe)

Upvotes: 1

Related Questions