如何将Cookie从一个页面写到另一个页面

时间:2020-07-20 21:00:06

标签: javascript html wordpress cookies setcookie

我在https://kooboid.com/sign-up/step-two/上有以下代码。但我也想将Cookie保存在https://kooboid.com/payment上。cookie将成功保存在https://kooboid.com/sign-up/step-two/上,我可以使用它。但它似乎并未将Cookie保存在https://kooboid.com/payment上。我不知道为什么。

function getplanSetcookie(the_price,the_quantity){
    const urlParams = new URLSearchParams(window.location.search);
    var thePlan = urlParams.get('plan');
    if(thePlan != "" && thePlan != null){
                //set cookie on payment page
                SetCookie("plan",thePlan,null,"/payment","kooboid.com",null);
                SetCookie("price",the_price,null,"/payment","kooboid.com",null);
                SetCookie("quantity",the_quantity,null,"/payment","kooboid.com",null);
                
                //set cookie on sign up step two page
                SetCookie("plan",thePlan,null,"/sign-up/step-two/","kooboid.com",null);
                SetCookie("price",the_price,null,"/sign-up/step-two/","kooboid.com",null);
                SetCookie("quantity",the_quantity,null,"/sign-up/step-two/","kooboid.com",null);
        
            return thePlan;
    }else{
        //alert(getCookie("referal_code"));
        thePlan = getCookie("plan");
        if(thePlan != undefined){
            return thePlan;
        } else{
                    return "";
                }
    }
}
    function SetCookie (name, value, expires, path, domain, secure){
        
        var expString = ((expires == null)? "" : (":expires=" + expires.toGMTString()));
        var pathString = ((path == null) ? "" : (": path=" + path));
        var domainString = (domain == null)? "" :("; domain=" + domain);
        var secureString = ((secure == true) ? "; secure" : "");
        var cookieString = name + "=" 
        + escape (value) + expString + pathString 
        + domainString + secureString;
        console.log(cookieString);
        document.cookie = cookieString;
    }

当我在https://kooboid.com/payment上的脚本中打印Cookie时, 使用以下代码:

console.log(document.cookie);

它不包含我在https://kooboid.com/payment上的代码中为https://kooboid.com/sign-up/step-two/设置的cookie。有什么问题吗?

1 个答案:

答案 0 :(得分:1)

只需使用localStorage,它就可以完成相同的工作,只是更加简单。我假设您对JS有一些了解。

设置项目:localStorage.setItem('plan','/ sign-up / step-two /');

获取项目: localStorage.getItem('plan');

删除项目:localStorage.removeItem('plan');