How can i get the destination url of a link on the web page in the javascript onbeforeunload event?

倖福魔咒の 提交于 2019-12-02 13:04:16

Instead of having a completely different set of headers/footers you could replace all links in certain areas with links that open in a new window like so:

$('#header a, #footer a').each(function() {
  $(this).attr('target', '_blank');
});

This is what I came up with to handle this and it is working for me.
Detects when user clicks on a page link then evaluates link to determine how to handle appropriately. It does not work for links typed in the browser address bar.

I use jquery magnific-popup (http://dimsemenov.com/plugins/magnific-popup/) to create a popup window (.popupForm-handleExitRequest in my code) that offers the user the option of opening link in same window (and losing their order data), in new window or returning to order form.

$('body a').click(function(e) {     
    //if link is reference to page element
    if ($(this).attr('href').charAt(0)=="#") {
        return;
    }

     //check if link is to same window    
     var pathname = window.location.pathname;
     var pathname2 = $(this).attr('href');
     pathname2 = pathname2.replace(/^.+\.\//, '');
     if (pathname.indexOf(pathname2) >= 0) {
        //link clicked is contained on same page
        //prevent page from getting reloaded & losing data
        e.preventDefault();
        e.stopImmediatePropagation();
        e.stopPropagation();    
        return;     
    }

    //link clicked on is another page
    if (hasMerchandise) {  //var to indicate user has items on order form       
        //give user options: leave page, open link in other page, stay, etc.
        // $('.popupForm-handleExitRequest').click();   //roll your own code    

        //prevent page from getting reloaded & losing data
        //in case user wants to cancel page change or open link in another window
        e.preventDefault();
        e.stopImmediatePropagation();
        e.stopPropagation();            
    } else {
        //load new page
        $(this).removeAttr('target');
    }       
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!