Angularjs $window.open popups being blocked

[亡魂溺海] 提交于 2019-11-30 20:32:21

You can't get rid of the popup blocker for scripted automated window.open. Only real user's call to action events will open a new window without being blocked by popup blocker. Imagine a situation in a site where there's no popup blocker in browser and javascript opens 100 popups in a loop. Would you like it ? It used to be there in our old good times like a virus but modern browsers are much smart and this annoyance is handled gracefully.

Chrome by default blocks popups that are not a result of user's direct action. In your case, I assume, the call to window.open is made inside a callback function. This makes it asynchronous and Chrome blocks it.

//before
$scope.userClicked = function(){
  $http.post('your/api/endpoint',{data:x}).then(function(r){
    $window.open(r.data.url,'window name','width=800,height=600,menubar=0,toolbar=0');
  });
}

However, there is a workaround to make this work. Instantiate your window outside the callback function and you can reference the variable to change the target url of that window in callback function.

//after
$scope.userClicked = function(){
  var popup = $window.open('','window name','width=800,height=600,menubar=0,toolbar=0');
  popup.document.write('loading ...');

  $http.post('your/api/endpoint',{data:x}).then(function(r){
    popup.location.href = r.data.url;
  });
}

You could quite simply create a directive to do this from within a click event content:

yourapp.directive('awesomeClick', ['$parse',function ($parse): ng.IDirective {
    return {
        restrict: 'A',        
        link: (scope, element:JQuery, attrs) => {
            var fn = $parse(attrs.awesomeClick);
            element.on('click', function (event) {

                // open the window if you want here 

                scope.$apply(function () {
                    fn(scope, { $event: event });
                });
            });
        }
    }
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!