简体   繁体   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?

Let me explain my scenario.让我解释一下我的情况。 I have a query string in my current page URl, if that exists then i need to store the URL in a cookie.我的当前页面 URl 中有一个查询字符串,如果存在,那么我需要将 URL 存储在 cookie 中。 Once i click sign in, i will be redirected to another page, then i will check if this cookie exist there or not, if it exist then it will redirect me back to the current page.单击登录后,我将被重定向到另一个页面,然后我将检查该 cookie 是否存在,如果存在则将我重定向回当前页面。

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

i am not able to save URL to cookie and use, can anyone help me in this?我无法将 URL 保存到 cookie 中并使用,有人可以帮我吗?

It's probably because multiple values are/need to be saved in the cookie.这可能是因为多个值/需要保存在 cookie 中。 So my advise would be to store it attached to an parameter like url={url} and create a function that can get the correct value like shown in the snippet below.所以我的建议是将它存储到一个像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);

The snippet won't work due to Stackoverflow rejecting the use of cookies in snippets.由于 Stackoverflow 拒绝在片段中使用 cookies,因此该片段将不起作用。

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

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