1

controller:

app.run(function ($rootScope, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function ($scope, $http) {     
        $templateCache.removeAll();
        alert("refresh.....");
        $http({
            url: '/angularjs-restful/check/check-session',
            method: "POST",
            data: {},
            isArray: false
        }).success(function(data, status, headers, config){
            alert("success.....");
            console.log('status: ' + status);
            console.log('data: ' + data);
        }).error(function(data, status, headers, config){
            alert('error');
        });        
        alert("end.....");
    });       
});

I need to make an AJAX call when a user hit f5 on keyboard or manually refresh the page with a mouse. How can I achieve this? the url is a rest service that either return true or false.

1 Answer 1

0

you can use window.onbeforeunload function to listen to the unload event which should fire on f5.

function ctrl($scope, $window) {
    angular.element($window).bind('beforeunload', function() {
        console.log('do ajax call');
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would instead recommend binding to the beforeunload event using the $window service in case you need to test your AJAX call through mocks. Example: jsfiddle.net/LkPJX
I tried and still does not work. How do I add your code onto the code that I posted above? When I refresh the page, the alert("refresh.....") is working fine and after the alert, I need to make an ajax call using $http to call a service...I added the code that you provided "angular.element($window).bind('beforeunload', function() { console.log('do ajax call'); });" but it does not run after alert has finished

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.