The business scenario

In the same main domain name (such as aaa.com), the sub-domain name (b.aaa.com,c.aaa.com) cannot transfer the address across the domain name. You need to close the browser and open it again to retrieve the address.

The solution

  • The front-end can achieve common browser storage method localstorage, here we use localstorage for offline localstorage.
  • The front-end can do the browser with the main domain name cross-domain value transfer localstorage and cookie can do, here we choose cookie. (Reason: LocalStorage requires iframe nesting to do this, the specific method is not explained here)

The specific methods

Make use of the domain property of the cookie. If the Cookie is set to. Aaa.com, all domain names ending with aaa.com can access the Cookie. Note that the first character must be “. .

<script type="text/javascript">  
    function setCookie(c_name,value,expiredays) {  
        var exdate=new Date();  
        exdate.setDate(exdate.getDate()+expiredays);  
        alert(exdate.getDate()+expiredays);  
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString())+"; path=/; domain=aaa.com";  
    } 
</script>
Copy the code

The practical application

Here the list page and detail page are separate project examples item.aaa.com detai.aaa.com

In the item.aaa.com

// select address id set [1,2,3]letAddressArr =[123] // Stored inlocalIn the StoragelocalStorage.setItem("addressArr"JSON. Stringify (addressArr)) / / fromlocalStorage and stored in cookieslet newAddressArr =localStorage.getItem('addressArr') // Store the address in a cookiesetCookie('addressArr',newAddressArr);
function setCookie(c_name,value,expiredays) {  
        var exdate=new Date();  
        exdate.setDate(exdate.getDate()+expiredays);  
        alert(exdate.getDate()+expiredays);  
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString())+"; path=/; domain=aaa.com";  
    } 
Copy the code

Get the address at detai.aaa.com

// Fetch the address from the cookiefunction getCookie(cookieName) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for(var i = 0; i < arrCookie.length; i++){
        var arr = arrCookie[i].split("=");
        if(cookieName == arr[0]){
            returnarr[1]; }}return ""; } // Apply addressArr to the pagelet addressArr = JSON.parse(getCookie("addressArr") // Store the cookie in localStoragelocalStorage.setItem("addressArr",JSON.stringify(addressArr))

Copy the code

other

Here, item.aaa.com transmits the value to the address detail.aaa.com, which realizes closing the browser and opening the browser again. The historical address selected last time still exists.

In the same way: Item.aaa.com and detail.aaa.com transmit and store values to each other, but they just use each other’s methods.