1

What I am doing: In my angular app, when the user clicks on a link, I am fetching the URL from the backend and launching with $window.open().

The problem: The Safari popup blocker is blocking $window.open(). If I do $window.open() outside of the success callback of the service call and in the controller, it works well. How do I get this working in the service success callback?

Plunker: http://plnkr.co/edit/aI4rvJJhP2XC5Mk1nK3t?p=preview

Code (relevant part):

index.html:

<body ng-app='myApp'>
  <div ng-controller="MyCtrl">
    <a href="javascript:;" ng-click="openLink()" target="_blank">Open Link</a>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="app.js"></script>
</body>

app.js:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', 'sampleService', '$window', '$log', function($scope, sampleService, $window, $log) {

  $scope.openLink = function() {

    // call the service
    sampleService.getURL().then(function(response) {
      $log.info('service response', response); // just checking the response
      $window.open(response, '_blank'); // this does not work! :(
    }, function(error) {
      $log.info('ERROR: ', error);
    });

    // $window.open('https://www.google.com', '_blank'); // works if placed here!
  };

}]);

myApp.service('sampleService', ['$q', function($q) {
  this.getURL = function() {
    return $q(function(resolve, reject) {
      setTimeout(function() {
        resolve('https://www.google.com'); // static URL, for now
      }, 2000); // send it back in 2 sec.
    });
  };
}]);

How do I fix this?

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • 1
    well when window.open is not triggered right after an event it is blocked. That is how pop up blockers work. – epascarello Mar 11 '16 at 02:26
  • @epascarello Oh wow! Is there any workaround for this at all, that you know of? – Rahul Desai Mar 11 '16 at 02:32
  • 2
    Open window onclick with message saying loading... when call comes back, replace the window location... but doing that makes no sense when you can just load the page in the pop up from the start. – epascarello Mar 11 '16 at 02:34
  • @epascarello Your workaround is awesome! Thank you so much! We made this decision since the API call is 3rd party for us and do not want to do it on page load. Fixed my Plunker: http://plnkr.co/edit/vI8o2oht4ulBVPtcr24o?p=preview – Rahul Desai Mar 11 '16 at 02:51
  • @epascarello I'd accept your answer if you want to post it to this question of mine. Or, would you like me to post it? – Rahul Desai Mar 11 '16 at 03:02
  • A reasonable way to solve this problem http://stackoverflow.com/a/10774233/7325372 – Sinan Yaman Mar 10 '17 at 07:57

0 Answers0