简体   繁体   中英

Detect browser tab close without jquery and send some data to php file

I have wrote a script that send some data to an external php file without jquery.

<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';

function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}

ca("pageview", "1", "male");


var params = Object.keys(p).map(function(k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')

const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();

req.onreadystatechange = function() {
    if (req.readyState == XMLHttpRequest.DONE) {
        alert(req.responseText);
    }
}
</script>

What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.

navigator.sendBeacon = navigator.sendBeacon || function () {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
    xhr.send();

xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
};

I found also this script but it gives me also no response from the response.php file as an alert:

    window.onbeforeunload = function()  {  
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);

// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
            //console.log(xhr.response);
            //console.log(xhr.responseText);
            alert(xhr.responseText);
        }
    }
};

xhr.send(null); 

    }

EDIT

I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.

window.onbeforeunload = function()  {  
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);

// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';

xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}

xhr.send(null); 

    }

You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message"; .

window.addEventListener("beforeunload", function(e) {
    //code        
});

Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM