The phenomenon of

The customer logged in to our system using different accounts (first A and then B) in the two tabs of the browser, and found that account B had not settled the account after adding the car, so he switched to the TAB of account A and clicked the settlement. As A result, account B’s money was deducted.

The analysis reason

Since the cookies in our system are planted under the same domain name, the account B that logs in later will replace the account A that logs in first, so that the cookies carried by users when sending requests will be B.

The solution

Suppose you already have a common request method in your project, which is encapsulated early in the architecture, usually called Request, where the core code is written.

The following process is for all accounts. Here account A is taken as an example

  • First check whether there is A cache for account A, if not, write, key is the unique flag (You can distinguish different users. The following uses accounts as an example), the value is the timestamp when the interface is triggered (it can beDate.now())
  • If there is A cache for account A, collect itlocalStorageYou can cache all the accounts (in this case, A and B) in an array
  • Go through the array and find the cache key that corresponds to the maximum timestamp, let’s say B
  • If the cache key corresponding to the maximum timestamp matches the current account (let’s say B), then it works fine
  • If the current operating account (let’s say A) is not the key corresponding to the maximum timestamp, no interface requests are sent, all caches in account A are cleared (in this case, A and B) and the page is refreshed
  • All the corresponding pages of account B now belong to account B

Simulation code

const request = () = > {
    if(!localStorage.getItem('A' account)) {
	    // If the cache does not exist, add it
	    localStorage.setItem('A' account.Date.now())
    } else {
	    // If the cache exists, iterate over localStorage and cache it in an array
	    for(let account in localStorage) {
		    arr.push({
		        [account]: localStorage.getItem(account)
		    });
	    }
	    // Encapsulate a method that iterates through each item in the array to find the account corresponding to the maximum timestamp
	    let max = getMax(arr);  // getMax method body omitted...

	    if(max === 'A' account) {
	        // If the account corresponding to the maximum timestamp is the account corresponding to the current TAB, the operation is normal, including updating the cache
	        localStorage.setItem('A' account.String(Date.now()))
	    } else {
	        // Otherwise, refresh the page, clear all accounts, and send no requests
	        location.reload();
	        for(let account in localStorage) {
		        localStorage.removeItem(account)
	        }
	        return; }}}Copy the code

Write in the last

This scheme may not be the best scheme, I hope it can throw off a brick!