window.在实时事件(使用socket.io)上打开时,当我的网站在一个窗口中打开时打开时



i在我的网站上具有一个实时功能,该功能从服务器端触发的socket.io事件上打开了新窗口( php/laravel 5.1 )。问题是,如果用户登录了我的网站并在一个以上的选项卡/窗口中打开它 - 新窗口。多次打开火,有人知道如何防止它?我的代码看起来像这样:

套接字侦听器:

socket.on('message', function (data) {
    data = JSON.parse(data);
    if(typeof data.data !== "undefined"){
        lead_data = data.data;
    }else{
        lead_data = data;
    }
    if(typeof lead_data !== "undefined" && (lead_data.event_name == "new_call" || lead_data.event_name == "new_unsaved_call")){
        if(lead_data.user_id == uid){
            window.App.openCallWindow(data);
        }
    }
});

openCallWindow函数:

openCallWindow : function(data){
    void(0);
    var lead_id = '';
    if(data && data.lead){
        lead_id = data.lead._id;
        window.open('/leads/callLead/'+lead_id,'new_lead'+Math.floor((Math.random()*999)+1), "height=800,width=1200" );
    }else if(typeof data.phone !== "undefined"){
        window.open('/leads/callLead/?phone='+data.phone,'new_lead'+Math.floor((Math.random()*999)+1), "height=800,width=1200" );
    }else{
        window.open('/leads/callLead/'+lead_id,'new_lead'+Math.floor((Math.random()*999)+1), "height=800,width=1200" );
    }
},

客户端活动选项卡解决方案:

您只需在选项卡处于活动状态(当前查看),才可以在窗口上调用窗口。可以这样做:

function isTabActive(){
    var state; 
    if (typeof document.hidden !== "undefined") {
        state = "visibilityState";
    } else if (typeof document.mozHidden !== "undefined") {
        state = "mozVisibilityState";
    } else if (typeof document.msHidden !== "undefined") {
        state = "msVisibilityState";
    } else if (typeof document.webkitHidden !== "undefined") {
        state = "webkitVisibilityState";
    }
    return document[state] != "hidden";
}

客户端侧面cookie

如果弹出窗口已经打开,您也可以使用cookie保存。饼干可以用JS编写和阅读。

服务器侧面解决方案with socket.io

如果您有用户帐户而不是IP!否则,对于具有相同IP的多个用户而言,它将是错误的。

var alreadySend={};
io.on('connection', function(socket)
{
   if(!alreadySend.hasOwnProperty(socket.handshake.address))
   {
      socket.emit("create popup", "popup1");
      alreadySend[socket.handshake.address]=true;
   }
});

重置
delete alreadySend[socket.handshake.address];

也可以在这里找到有关使用socket.io

获得IP的更多详细信息

您可以使用状态并通过

之类的函数访问它
function isTabActive(){
    var state; 
    if (typeof document.hidden !== "undefined") {
        state = "visibilityState";
    } else if (typeof document.mozHidden !== "undefined") {
        state = "mozVisibilityState";
    } else if (typeof document.msHidden !== "undefined") {
        state = "msVisibilityState";
    } else if (typeof document.webkitHidden !== "undefined") {
        state = "webkitVisibilityState";
    }
    return document[state] != "hidden";
}

最新更新