关闭浏览器或者关闭使用window.open打开的页面时添加监听事件

最近工作中有个需求:点击按钮时打开一个页面,此处取名为page1,打开页面的前提条件是如果有人已经打开过page1页面并且没有关闭时请求ajax判断session是否为空,如果为空则将用户名和文档id存入session,如果不为空则提示已有人打开此页面。

$(function(){
        addassbutton('_FORM_PF_sp_f22860');
        function addassbutton(textid){
                $('#'+textid).after("<br/><input type='button' id='visualButton' value='' style='background:url(/fileftp/2013/05/2013-05-13/U32P4T47D26207F980DT20130513164525.gif) no-repeat; border:0px;108px;height:28px;padding-bottom:16px;margin-left:5px;'/>");      
        }
        $("#visualButton").bind('click',function(){
           var ztselected = $("select[name=_FORM_PF_sp_f22820] option:selected").val();
           if(ztselected==''){
                 alert("请先选择专题名称");
                 return;
           }else{
                if(did_gspsass !==''){
                    $.ajax({
                        //async:false,
                        url: '/api/checkSess/' + username_gspsass + '/' + did_gspsass,
                        type: 'get',
                        dataType: 'json',
                        success:function(res){
                            console.log(res);
                            console.log(res.username === username_gspsass);
                            if(res.session==='true'){
                                openWin();
                            }else{
                                //alert("不允许多人同时操作,紧急情况请联系<strong>" + res.username + "</strong>");
                                alert("不允许多人同时操作");
                            }
                        }
                    })
                }else{
                    openWin();
                }
           }
        });      
});

  function openWin(){
       window.open('/gsps/visualization/visual.html','newwindow','height=800,width=1500,top=0,left=0,toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
  }

点击"可视化编辑"按钮时先请求ajax时会出现window.open弹窗被chrome拦截的问题(参考1链接),原因:由于window.open的执行时机,window.open在ajax中执行,无论是同步还是异步,等待ajax返回结果都需要一定的时间,当得到返回的结果然后再执行window.open时,chrome认为是不友好的行为,非用户主动点击打开弹窗),所以会被屏蔽。

解决方法一:允许被阻止的页面打开,

解决方法二:先打开一个空白页,然后等ajax回来的结果,拿到链接地址,替换掉之前空白页的url(参考2链接)。

注意: 使用解决方法一时,用户第一次打开页面newwindow(不关闭),当用户再次点击按钮触发时没有反应,因为newwindow已经打开,但是需要用户手动去找打开的newwindow,不能自动弹出已经打开的页面,容易让用户以为程序出现了问题,不利于用户体验,如若有解决方法,请在评论区留言,多谢!!!

           使用解决方法二时,用户第一次打开页面newwindow(不关闭),当用户再次点击按钮触发时会弹出一个空白页覆盖newwindow,暂未找到解决方法,如若有解决方法,请在评论区留言,多谢!!!

 

不调用ajax时,代码如下:

点击按钮时会打开visual.html页面(名称为page1),并且再次点击按钮时打开的还是page1页面,会自动弹出;

参考:1、http://blog.csdn.net/xufaxi/article/details/6647952

        2、https://segmentfault.com/q/1010000006760018/a-1020000006765547

        3、http://www.cnblogs.com/catalina-/p/5846353.html

原文地址:https://www.cnblogs.com/loveamyforever/p/6485106.html