1

Angular JS provides clean method for closing browser window.

$window.close()

Seemingly valuable under the hood actually it only wraps the window object with angular service:

function $WindowProvider() {
  this.$get = valueFn(window);
}

https://github.com/angular/angular.js/blob/master/src/ng/window.js

Few years ago there've been a security update of web browsers and now closing windows not opened by a script is forbidden, so execution of the $window.close() method in Chrome or Firefox throws the exception (Scripts may close only the windows that were opened by it.)

Here's great SO post describing it: https://stackoverflow.com/a/19768082/3775079

Solution provided by community is to open the same window and then close it:

var popup = window.open(location, '_self', '');
popup.close();

Unfortunately this solution applied to angular code doesn't work to me:

foo.controller('barCtrl',
    function barCtrl($scope, ) {
        var initialize = function () {
            var popup = $window.open(location, '_self', '');
                popup.close();
        }

        initialize();
    }
);

It causes an infinite loop of window refresh.

How can I properly execute window.close method after security update in Angular solutions?

Community
  • 1
  • 1
Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108
  • Yes, due to said security updates you can't close windows that weren't opened programmatically. There's nothing you can do to change that. – JJJ Jul 11 '16 at 15:01
  • @Juhana Okay, in vanilla js there's a workaround, but what about doing it in Angular? Is there any trick to do this? – Arkadiusz Kałkus Jul 12 '16 at 07:17
  • Angular is a JavaScript library. If it's not possible in JS, it's not possible in Angular (or in jQuery or React or Meteor or ...) Your options are listed in the other question (browser extension or add-on.) – JJJ Jul 12 '16 at 13:57
  • @Juhana It's obvious that if something isn't feasible in JS it isn't feasible in Angular, but what about this trick with opening window and closing it using obtained handle (`var popup = window.open(location, '_self', ''); popup.close();`)? People say it does work in vanilla, but it doesn't in Angular. Is there any way to use it in Angular? – Arkadiusz Kałkus Jul 12 '16 at 14:04
  • It doesn't work in vanilla. – JJJ Jul 12 '16 at 14:29

0 Answers0