开发者

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

开发者 https://www.devze.com 2023-02-14 08:05 出处:网络
This is the sample code: in the pop up : <body onunload=\'stopThisAndChangeParentInstead()\' > <a href=\'MY_URL\'> Click here </a>

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 开发者_如何学JAVAalready know it.


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.


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)


  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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消