shopify liquid 无法直接访问浏览器 localstorage,因此需借助 cart attributes 在服务端持久化密码状态,再通过 liquid 条件渲染受保护内容,实现安全且可刷新的密码验证流程。
shopify liquid 无法直接访问浏览器 localstorage,因此需借助 cart attributes 在服务端持久化密码状态,再通过 liquid 条件渲染受保护内容,实现安全且可刷新的密码验证流程。
在 Shopify 中为集合页面添加密码保护时,一个常见误区是试图在 Liquid 模板中直接读取 localStorage(例如 localStorage.getItem("password")),但这根本不可行——因为 Liquid 是服务端渲染语言,执行时 JavaScript 尚未运行,localStorage 完全不可见,且 <script> 中混用 {% %} 语法会导致模板解析失败(如报错 unexpected character '%')。
✅ 正确方案:将密码状态“同步”到服务端可访问的数据源 —— 这里推荐使用 Cart Attributes(购物车属性)。它既无需创建用户账户,又能在服务端被 Liquid 安全读取,且支持跨页面、跨刷新持久化(只要 cart 未清空)。
实现步骤
-
前端提交密码并写入 cart attributes
在密码表单提交时,通过 fetch('/cart/update.js') 将密码作为自定义属性存入购物车:
document.getElementById('password-form').addEventListener('submit', async function(e) {
e.preventDefault();
const passwordInput = document.getElementById('collection-password');
const password = passwordInput.value.trim();
if (!password) return;
try {
await fetch('/cart/update.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
attributes: { 'collection_password': password } // 建议使用语义化 key,避免硬编码 "password"
})
});
location.reload(); // 刷新后 Liquid 可读取更新后的 cart.attributes
} catch (err) {
console.error('Failed to save password:', err);
}
});-
Liquid 模板中条件渲染内容
在 collection.liquid 或对应模板中,使用 cart.attributes 进行服务端校验(注意:此处比较应使用安全方式,见下文注意事项):
{% if cart.attributes.collection_password == 'my-secret-phrase' %}
{% include 'protected-collection' %}
{% else %}
{% include 'protected-collection-form' %}
{% endif %}⚠️ 关键注意事项
- 不要在前端暴露明文密码校验逻辑:上述示例中,密码值 'my-secret-phrase' 应严格保密,切勿在 JS 中硬编码或通过 API 返回原始密码。所有敏感比对必须在服务端(Liquid)完成。
- 避免使用 password 作为属性名:Shopify 对 password 等关键词可能有内部限制或过滤,推荐使用如 collection_password、access_token 等明确前缀的键名。
-
清除密码机制:提供“退出”按钮,通过设置属性为空来重置访问状态:
fetch('/cart/update.js', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ attributes: { 'collection_password': null } }) }).then(() => location.reload()); - 兼容性与兜底:若用户禁用 JavaScript,此方案失效;建议配合基础 HTTP Basic Auth 或第三方密码应用作为备用方案。
该方法兼顾安全性、简洁性与 Shopify 生态兼容性,是当前无插件、无后端服务前提下最稳健的客户端密码保护实践。

















