繁体   English   中英

如何将当前的 URL 存储在 cookie 中,并使用该 cookie 检查其他页面,如果可用,然后重定向到 JS 中的相同 URL?

[英]How to store current URL in cookie, and use that cookie to check in other page, if available then redirect to the same URL in JS?

让我解释一下我的情况。 我的当前页面 URl 中有一个查询字符串,如果存在,那么我需要将 URL 存储在 cookie 中。 单击登录后,我将被重定向到另一个页面,然后我将检查该 cookie 是否存在,如果存在则将我重定向回当前页面。

if(queryString = 'data'){
  document.cookie = window.location.href;
  let abc = document.cookie;
}

我无法将 URL 保存到 cookie 中并使用,有人可以帮我吗?

这可能是因为多个值/需要保存在 cookie 中。 所以我的建议是将它存储到一个像url={url}这样的参数上,并创建一个 function 可以得到正确的值,如下面的片段所示。

 let url = window.location.href; console.log("Default url:", url); document.cookie = `url=${url}`; let wrong = document.cookie; console.log("Full cookie:", wrong); function getCookie (name) { let value = `; ${document.cookie}`; let parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } let right = getCookie("url"); console.log("Only url:", right);

由于 Stackoverflow 拒绝在片段中使用 cookies,因此该片段将不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM