【问题集】window.open使用被拦截问题

来源:互联网 发布:win10系统安装mac os 编辑:程序博客网 时间:2024/06/01 09:49
需求:
   在调取接口后,将响应内容在新的tab页展示。

实现思路:
    在响应回调中通过window.open()方法,打开新的tab。

问题:
    因为浏览器拦截导致新tab无法打开。

方案:
    1、在网上搜了主要解决方案:
           <input type="button" id="btn" value="保存" ng-click="save();" />        在点击事件中:
        a、创建a标签,并触发click事件;
  .     var a = document.createElement("a");            a.setAttribute("href", url);            a.setAttribute("target", "_blank");            document.body.appendChild(a);            a.click();

        b、创建form表单,触发submit
       var f=document.createElement("form");        f.setAttribute("action" , url );        f.setAttribute("method" , 'get' );        f.setAttribute("target" , '_black' );        document.body.appendChild(f)        f.submit();
这两种方案在不延时的情况下,是可以重新打开tab的,因为浏览器会认为这是用户的操作。
  但是当我将这段代码延时1s执行时,tab就会被浏览器拦截。~~可能浏览器认为是广告吧...
  而http请求肯定是有延时的,因此这种方案不可行。于是有了方案2:
2、在点击事件触发时先调用window.open()方法,打开新的tab,然后在响应回调中,设置新打开tab的href。
            var new_window = null;             $scope.save= function () {                new_window = $window.open();                commonService.sendRequest(Api.choosePayChannel, 'POST', {                    orderNo: $scope.orderNo,                    payType: $scope.currentPlatform                }).then(function (resp) {                    var respData = resp.data;                    if (respData) {                        if (respData.type == 'html') {                             new_window.document.write(respData.result);                        } else if (respData.type == 'img') {                            var url = $state.href('smsPay', {codeUrl: respData.result, orderId: $scope.orderNo});                             new_window.location.href = window.location.origin+window.location.pathname+url;                        }                    }                }, function (error) {                    new_window.close();                    commonService.showErrorTip(error);                });            };


原创粉丝点击