Article

Save browsing history to a cookie

https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
Copy to clipboard

Sometimes we may want to keep a record of every page that a user has visited on our website.

To do this we can write: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/cookies/ex19.js?actionable=true

The code above will first check if there is a cookie named history. If it finds this cookie it will retrieve its value which is always text that we can convert to an array.

We can add the current page to this array.

It will then store this new array as text in the history cookie.Because cookies can only be store text we use the function JSON.stringify() to convert our array to text.

Conversely we use the function JSON.parse(pages) to convert our stored text to an array.If the cookie is non existent then we will create the cookie and add the current page as its first value like so:Cookies.set('history', JSON.stringify([current_page]))

<script>
$(document).ready(function(){
  XT1
});
</script>
Copy to clipboard
Send to Live Demo

Live demo

<script>    
$(document).ready(function() {
  XT1
});
</script>
<script>
  
</script>
Copy to clipboard
Press the Run Demo button to execute the scripts above.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Your browser is too small

Resize your browser to be at least 769px wide.