如何从浏览器向服务器发送消息“页面将关闭”?

时间:2015-08-29 07:25:06

标签: javascript html

我想为每个html文档添加一个脚本(JavaScript),它向服务器发送两条消息:

  • 页面已打开
  • 页面将关闭(此消息包含页面打开的时间)

应在文档加载时(或加载完成后)发送开放消息。这很容易。

当从浏览器的视口卸载文档时,应发送关闭消息。 (用户点击没有target =“_ blank”的链接;用户关闭浏览器标签/窗口;用户重新加载页面;用户退出浏览器;任何使页面消失的内容)

我试过这种方式:

//================================================================================
//Global Variables
//================================================================================
gl = {}; //container for global variables (1 scalar and 1 function)
gl.start = Math.floor(Date.now()); //timestamp of page-loading


//================================================================================
//function: Send message to server
//================================================================================
gl.sendData = function (action) {
    var message = {
        'href'     : window.location.href,
        'height'   : $(window).height(),
        'width'    : $(window).width(),
        'action'   : action,       //can be 'open' or 'close' (i.e. 'load' and 'unload')
        'rand'     : Math.random() //random number to outwit cache
    };
    if (action == 'close') {
        //how long was the page open? [milliseconds]
        message.duration = Math.floor(Date.now()) - gl.start;
    };
    window.alert(action); //debugging: show if gl.sendData is executed
    $.ajax({
        'url'     : 'http://' + window.location.hostname + '/path/to/script.pl',
        'data'    : message,
        'success' : function(){}, //not interested in server's answer
        'error'   : function(){}  //errors will be ignored
    });
};


//================================================================================
//Things to do as soon as page load is complete
//================================================================================
$(document).ready(function(){

    //send message "page did open"
    gl.sendData('open'); 

    //add event-handler to send the message "page will close" when the page is closing
    $(window).on("unload", function() {
        gl.sendData('close'); 
    });
});

页面打开时发送消息非常正常。但浏览器不发送关闭消息。

我发现了这个事实:

  • “卸载”似乎是正确的事件。页面关闭时会弹出警报消息。
  • “beforeunload”不起作用,因为它没有被触发(Mac上的Safari,点击导航到另一个页面的链接)
  • 在页面加载时发送ajax-request,所以看起来没问题。
  • 当页面关闭时,ajax-request不会向服务器发送数据。

我的问题:

在从浏览器卸载文档时,有没有办法向服务器发送按摩? 我想将显示的页面持续时间发送到服务器。还有另一种方法吗?

1 个答案:

答案 0 :(得分:4)

当页面关闭时,在所有浏览器中都有100%可靠的方法将数据发送到服务器。

随着浏览器中webSockets的出现和普遍可用性,有些人正在使用从客户端到服务器的webSocket连接作为跟踪它的方法。打开页面时,它会与服务器建立webSocket(或socket.io)连接。此连接在页面持续时间内保持打开状态。当用户离开页面或关闭浏览器时,浏览器将关闭webSocket。然后,服务器可以看到webSocket已关闭,并可以将其标记为页面关闭的时间。

另一种效率低于webSocket连接的可能性是开放网页定期通过Ajax轮询服务器(比如每30秒左右宣布该页面仍处于打开状态)。当服务器看到轮询停止时,它会认为页面已关闭。

这两种技术都需要与服务器定期连接才能进行此跟踪(例如,无法用于跟踪离线使用情况)。