代码之家  ›  专栏  ›  技术社区  ›  Rod

onbeforeunload消息的github示例透视

  •  1
  • Rod  · 技术社区  · 7 年前

    following example onbeforeunload 信息直截了当?

    它能短一点还是容易一点?有没有比窗口事件更有角度的方法?

    angular.module('TestApp', [])
    .factory('beforeUnload', function ($rootScope, $window) {
        // Events are broadcast outside the Scope Lifecycle
    
        $window.onbeforeunload = function (e) {
            var confirmation = {};
            var event = $rootScope.$broadcast('onBeforeUnload', confirmation);
            if (event.defaultPrevented) {
                return confirmation.message;
            }
        };
    
        $window.onunload = function () {
            $rootScope.$broadcast('onUnload');
        };
        return {};
    })
    .run(function (beforeUnload) {
        // Must invoke the service at least once
    });
    function TestController($scope) {
        $scope.$on('onBeforeUnload', function (e, confirmation) {
            confirmation.message = "All data willl be lost.";
            e.preventDefault();
        });
        $scope.$on('onUnload', function (e) {
            console.log('leaving page'); // Use 'Preserve Log' option in Console
        });
    }
    <!DOCTYPE html>
    <html data-ng-app="TestApp">
    <head>
    <script src="http://code.angularjs.org/1.2.9/angular.js"></script>
    </head>
    <body data-ng-controller="TestController">
    This is a test
    <a href="http://www.google.com/">Google</a>
    </body>
    </html>
    1 回复  |  直到 7 年前
        1
  •  0
  •   I_Al-thamary    7 年前

    这个问题与安全性有关,它与最新版本的chrome和firefox不兼容。 请参阅: Crossbrowser onbeforeunload? jQuery beforeunload custom pop up window for leaving a page

    <!DOCTYPE html>
    <html>
    <body onbeforeunload="return myFunction()">
    
    <p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
    
    <a href="https://en.wikipedia.org">Click here to go to wikipedia.org</a>
        
    <script>
    function myFunction() {
      return "Write something clever here...";
    }
    </script>
    
    </body>
    </html>