How to use Unload with angular JS?

Asked

Viewed 90 times

0

Unload should be called when leaving the page and hit any url from another site.

In an old version, without Angular JS, doing this, works normal, it calls the request, when I turn on the debug the API is entering...

        window.onbeforeunload = function(e) {
                e = e || window.event;
                e.preventDefault = true;
                e.cancelBubble = true;
                if (shouldAsk)
                    e.returnValue = 'Se você sair agora desta atividade, irá perder automaticamente uma tentativa!!';
            };

            var didSelectReturn = false;
            $(window).unload(function(){
                if (!didSelectReturn && shouldAsk) {
                    giveup(function(){

                    }, false);
                }
            });

    function giveup(callback, async)
            {
                async = typeof async !== 'undefined' ? async : true;
                if(_started!=null)
                {

                    window.clearInterval(myTimer);
                    var seconds = secondsCount;

                    _started = null;

                    sendDataWithAction_type(LoggeUserID,"quiz", json.id, "time", "giveup", "0", "0", seconds, function(){ // success

                        callback();
                    }, function(){ // error
                        //NSLog(@"sendDataWithAction_type error");
                        callback();
                    }, async);
                    //--
                }
                else{
                    callback();
                } 

function sendDataWithAction_type(user_id, action_type, action_id, data_type, value, start, end, seconds_time, success, error, async) {

    async = typeof async !== 'undefined' ? async : true;
    var GETparams = "user_id="+user_id;
    GETparams += "&action_type="+action_type;
    GETparams += "&action_id="+action_id;
    GETparams += "&data_type="+data_type;
    GETparams += "&value="+value;
    GETparams += "&start="+start;
    GETparams += "&end="+end;
    GETparams += "&seconds="+seconds_time;
    var checkToken = readCookie("gutentoken");
    var checkEmail = readCookie("gutenemail");
    var params = "gutentoken="+checkToken+"&gutenemail="+checkEmail;
   var url = "/"+FOLDER_ADM+"/add-bigdata.php?"+GETparams;

    $.ajax({
        url: url,

        type: "POST",
        data: params,
        dataType: "json",
        async:async,
        timeout:60000,
        success: function(data) {
            // if (data.status=="200") {
            //     clearInterval(intervalTime);
            // } else {
            //     clearInterval(intervalTime);
            // }
            seconds = 0;

        },
        error: function(data) {

            if(typeof window.parent.data_form !== 'undefined'){
                if(data.status != 404 && window.parent.data_form.withOutInternet == false){
                    window.parent.data_form.withOutInternet = true;
                }
            }
            alert("Erro ao enviar informações, você pode estar sem internet, tente novamente.");
        }
    });

}

Now, when I put Angularjs, the async request = false is not entering when I leave the system and access a google address for example, the API is not called. What I’m doing wrong?

$scope.init = function() {

 window.onbeforeunload = function(e) {

                        if(!$scope.btnReturn){

                            e = e || window.event;
                            e.preventDefault = true;
                            e.cancelBubble = true;
                            e.returnValue = 'Se você sair agora desta atividade, irá perder automaticamente uma tentativa!!';
                        }
                    };

                    window.addEventListener('unload', function() {

                          var data = {
                              activity_id: atividade,
                              timeoff: $scope.timeOff.tempo_total,
                              date_steps: $scope.dateSteps
                          };

                        var url = "api-games/give-up";

                        var dados = {
                            csrf_token: csrf,
                            user_id: data_form.user_id,
                            activity_id: data.activity_id,
                            timeoff: data.timeoff,
                            date_steps: data.date_steps

                        };


                        $.ajax({
                            type: 'POST',
                            data:dados,
                            async: false,
                            timeout:60000,
                            url: url + '/?rand=' + randUrl()
                        });

                    });

 };


 $scope.init();

1 answer

0


Solved using pure javascript as follows:

$window.onbeforeunload = function(e) {

                        if(!$scope.btnReturn){

                            e = e || window.event;
                            e.preventDefault = true;
                            e.cancelBubble = true;
                            e.returnValue = 'Se você sair agora desta atividade, irá perder automaticamente uma tentativa!!';
                        }
                    };

                    if (!$scope.final_game && $scope.started_game) {
                        window.addEventListener('unload', sendData, false);
                    }

                    function sendData() {

                        if(!$scope.btnReturn) {
                            var url = "api-games/give-up";

                            var data = {
                                activity_id: atividade,
                                timeoff: $scope.timeOff.tempo_total,
                                date_steps: $scope.dateSteps
                            };

                            var dados = {
                                token: getTokenGames(url),
                                csrf_token: csrf,
                                user_id: data_form.user_id,
                                activity_id: data.activity_id,
                                timeoff: data.timeoff,
                                date_steps: data.date_steps

                            };

                            var client = new XMLHttpRequest();
                            client.open("POST", url, false); 
                            client.send(JSON.stringify(dados));
                        }
                    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.