You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify:产品页设置JS Cookie后购物车页无法读取,需实现继续购物跳转

问题分析与解决方案

需求说明

  • 将用户访问的最新产品页面URL存储到Cookie中
  • 购物车页面点击「CONTINUE SHOPPING」按钮时:
    • 若Cookie存在有效值,跳转至该产品页面
    • 若Cookie无有效值,跳转至店铺首页

当前代码问题

现有代码在产品页能成功存储Cookie,但购物车页面读取Cookie时返回Undefined,无法获取到之前存储的产品URL。

问题原因排查

  1. Cookie路径限制:默认情况下jQuery Cookie插件会把Cookie路径设为当前页面的路径(比如产品页路径是/products/xxx,Cookie路径就为/products),购物车页路径是/cart,不在同一路径下,导致无法读取Cookie。
  2. 缺少按钮跳转逻辑:现有代码仅在购物车页打印Cookie值,没有绑定「CONTINUE SHOPPING」按钮的点击跳转逻辑。

修正后的代码

<script src="https://code.jquery.com/jquery-3.7.0.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" type="text/javascript"></script>
<script type="text/javascript">
    // 产品页存储Cookie,设置根路径确保全站可访问
    if (window.location.href.indexOf("products") > -1) {
        var latestProductUrl = window.location.href;
        // 设置path为"/",让Cookie在整个网站域名下都能被读取
        $.cookie("lastProductUrl", latestProductUrl, { path: "/" });
        console.log('已存储产品URL: ' + $.cookie("lastProductUrl"));
    }

    // 购物车页绑定按钮点击事件
    if (window.location.href.indexOf("cart") > -1) {
        // 绑定CONTINUE SHOPPING按钮的点击事件
        $('button:contains("CONTINUE SHOPPING")').on('click', function(e) {
            e.preventDefault(); // 阻止默认跳转行为
            var lastProductUrl = $.cookie("lastProductUrl");
            if (lastProductUrl && lastProductUrl.indexOf("products") > -1) {
                // Cookie存在有效产品URL,跳转至该页面
                window.location.href = lastProductUrl;
            } else {
                // Cookie无效或不存在,跳转至店铺首页(替换为你的店铺首页URL)
                window.location.href = "/";
            }
        });
    }
</script>

关键修正点

  • Cookie路径配置:添加{ path: "/" }参数,让Cookie在整个域名下的所有页面都能被读取,解决跨路径无法获取Cookie的问题。
  • 按钮事件绑定:新增按钮点击监听逻辑,替换原有仅打印日志的代码,实现跳转功能。
  • 有效性校验:跳转前额外校验Cookie中的URL是否包含产品页标识,避免跳转到无效页面。

内容的提问来源于stack exchange,提问作者Kamalpreet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:33:15