前言,在项目中忽然间遇到了一个状况,一样的代码怎么有点地方window.open()打开的新页面不被拦截,有的地方又被拦截了呢,我百思不得其解,因而上网查了下,终于明白这是什么缘由了,下面一一讲述。php
如今,先讲下打开新页面的方法,主要有一下几种:html
第一种:a标签 '<a href="test.php"target="_blank">,target="_blank"为打开一个新的窗口,不然,为当前页面跳转到指定页面;jquery
第二种:form表单'<form action="drag.html" method="get" id="form" target="_blank"/></form>',提交表单便可打开新页面,target='target',则将表单信息提交至新打开的指定页面,不然当前页面跳转到指定页面;ajax
第三种:window.location 执行window.location='test.php',页面将跳转到指定页面。json
第四种:window.open(url);执行window.open('test.php'),将会打开心新的指定页面,当前页面不变。
浏览器
如今在对浏览器打开新页面的问题作一下简单小结,浏览器对于用户点击行为直接打开的页面通常不会拦截,好比不经过JS直接点击a、提交form表单,浏览器是不会阻止其跳转页面或者打开新页面行为的。可是对于JS打开新页面浏览器会好好审核的,以下面的例子,不少浏览器回去拦截。async
<form action="test.php" method="get" id="form" target="_blank"/>//target为弹出新窗口 <input type="hidden" name="name" value="ck"> <input type="hidden"id="pwd" name="id" value="123456"> <input type="submit" style="display:none;" value="提交"> </form> <button id="btnSubmitForm">点击我提交表单</button> <button id="btnAjaxSubmitForm">点击我发送ajax提交表单</button> <script src="js/jquery-1.8.0.min.js"></script> <script> $("#btnSubmitForm").on('click,function(){ window.open(url); $("#form").submit(); }) //下面这种代码是系统自动执行的默认会被拦截。 window.open(url); $("#form").submit(); $("#btnSubmitForm").trigger('click'); $.post(url,json,function(){ //下面两种也会被浏览器当成广告给拦截掉。浏览器认为ajax发送以后执行的如下事件等同于系统自动触发的都会去阻止。 window.open(url); $("#form").submit(); $("#btnSubmitForm").trigger('click'); }) </script>
上面是最简单的2种会被浏览器当成广告的状况,那么该如何避免避免这种状况呢,很简单,咱们能够经过如下方法:post
<form action="test.php" method="get" id="form" target="_blank"/>//target为弹出新窗口 <input type="hidden" name="name" value="ck"> <input type="hidden"id="pwd" name="id" value="123456"> <input type="submit" style="display:none;" value="提交"> </form> <button id="btnSubmitForm">点击我提交表单</button> <button id="btnAjaxSubmitForm">点击我发送ajax提交表单</button> <script src="js/jquery-1.8.0.min.js"></script> <script> // 第一种方法点击直接触发window.open()或者$(form).submit(); $("#btnSubmitForm").on('click,function(){ window.open(url); $("#form").submit(); }) //第二种方法 如果点击发送ajax触发方法,这里要强调一下无论是自动发送ajax仍是手动发送ajax成功以后调用的方法内部用Window.open()或者$(form).submit()均可能会被认为是广告。下面个人解决方法是,手动同步发送ajax,以后 将ajax的值赋予变量,再在ajax方法以后调用Window.open()或者$(form).submit()就能够避免这种问题。 $("#btnAjaxSubmitForm").on('click,function(){ $.ajax({ url: "test.php", async: false, success:function(){ } }) Window.open()或者$(form).submit() }) 这样就没问题了。 </script>