window.open打开新窗口,防止浏览器阻止弹窗解决办法

来源:互联网 发布:有关人工智能电影 编辑:程序博客网 时间:2024/05/01 11:01

打开新窗口,以下常用3种方式:

//1.弹出窗口window<strong><span style="font-family:Microsoft YaHei;"><strong><span style="font-family:Microsoft YaHei;"></span></strong><img src="http://img.blog.csdn.net/20160106125415528?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="http://img.blog.csdn.net/20160106125441713?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />使用:可以直接打开页面或action访问映射视图</span></strong><pre name="code" class="html"><strong><span style="font-family:Microsoft YaHei;"><strong><span style="font-family:Microsoft YaHei;"> eg:</span></strong></span></strong><div><span style="font-family:Microsoft YaHei;"> window.open ('http://www.webcjs.com ','newwindow','height=500,width=800,top=0,left=0,</span>  </div><div><span style="font-family:Microsoft YaHei;"> toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no')</span></div>
window.open("toLottery.action");
<span style="font-size:14px;color:#FF0000;"> 注:url可以用xxx.jsp或xxx.action,例如index.jsp或toLottery.action</span>
 //2.模拟表单形式打开新窗口:创建form,添加基本属性,表单提交
 var f=document.createElement("form");
 f.setAttribute("action" , url );
 f.setAttribute("method" , 'post' );
 f.setAttribute("target" , '_black' );
 document.body.appendChild(f);
f.submit();
//3.创建超链接:创建a元素,增加属性,绑定一个模拟点击事件
  3.1  
 var a = document.createElement("a");
 a.setAttribute("href", url);
 a.setAttribute("target", "_blank");
 a.setAttribute("id", "openwin");
 document.body.appendChild(a);
 a.click();
 3.2  
var a = $("<a href='url' target='_blank'></a>").get(0);
 var e = document.createEvent('MouseEvents');
 e.initEvent('click', true, true );

总结:无论用那种方式弹窗,只要是用户发起访问浏览器弹窗都不会被浏览器阻止弹出,即用户直接触发事件,弹出窗口的情况; --------1.-浏览器不会阻止弹框情况

eg:

$("#id").click(function(){

  window.open("弹出新窗口链接");

});

如果自动执行,浏览器认为是广告,阻止弹出。比如:通过ajax请求后台,通过回调函数success执行弹窗,浏览器将会阻止弹出新窗口。------2.浏览器会阻止弹框情况

eg:

$.ajax({

  type:"post",

  dataType:"json",

  data :{},

  url:"访问后台链接",

  success : function(data){

     window.open("弹出新窗口链接");

   }

});

建议:为了能够正常弹出,尽量给用户触发点,由用户自行发起,像第一种情况一样。

0 0