首页 > 解决方案 > Pass a clean cookie variable in Javascript / Vue JS

问题描述

My scenario is this.

I have the following variable:

_s.$cookie.set('videoURL', this.sample_url)

Now, when I looked into Chrome dev tools on Application -> Cookies, this is what I see.

enter image description here

As you may see, there is special characters in between the URLs, probably replacing the "/".

How do you clean this such that is passes a clean URL (eg. http://helloworld.com)?

UPDATE:

After the first answer below, I revised my code. However the same special characters still exist.

my code now is as follows. I'm using Vue JS.

  urlEncoded = encodeURIComponent('http://helloworld.com')
  decodeURL = decodeURIComponent(urlEncoded)
  _s.$cookie.set('videoURL', decodeURL)

UPDATE 2

After passing the cookie variable to class variable, finally saw that the URL is now clean of special characters.

  _s.videoURL = _s.$cookie.get('videoURL')
  console.log(_s.videoURL)

标签: javascripturlcookiesvuejs2

解决方案


You can't store it as a clean url since it has characters that aren't allowed in a cookie.


An option is to encode / decode the value when write/read the cookie

var url = "http://helloworld.com"
var url_encoded = encodeURIComponent(url)

console.log(url_encoded)

console.log(decodeURIComponent(url_encoded))


Updated after question edit, Vue JS is being used.

Here is two addons for Vue that might solve it for you


And as commented, to cached a video URL across different pages of the website, localStorage might be more appropriate.


推荐阅读