简体   繁体   中英

How to avoid same cookie being written multiple times when multiple window is open

I have a simple chat room web app. I want to be able to save chat history into user's cookie using javascript. The problem I just encounter is when user open more than one window, he will be saving chat message multiple times into his cookie. It must be very confusing reading this, please see example below:

There are only two users A and B in the chat room, A is acting normal but B has two windows open, both in the same chat room page. A says "Good Morning", B says nothing and what he see is:

A: Good Morning

Nothing is wrong so far, but when B is saving this into his cookie, because he has two windows open, this message will be saved twice into his cookie. So the next time he come to the chat room, the chat history he sees will be:

A: Good Morning

A: Good Morning

If B opens n windows at the same time, the message is saved n times.

A solution I have in mind is when saving message into cookie, check if the last message in the cookie is the same as the one being saved, if they are the same, don't save it again.

But for cases when a user is truly sending same message multiple times, this will omit the duplicated messages which it shouldn't.

How is this usually solved? I guess users usually can't open two chat room page at the same time but I allow them to do so.

Assign each message a unique ID on the server. Check the local chat history to see if that id exists anywhere in it already.

You could save the time stamp for each message and if the message and the time stamp both matches, then it is a duplicate message.

Here is an example, how to get a timestamp in JavaScript

我说说我的想法,因为每个窗口都有cookie,您将进入拖曳历史记录。我认为您可以为每个历史记录设置时间标记。每个人都无法发送拖曳或多条消息。您可以测试时间标记。然后判断此消息需要保存或不保存。

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