A better code for a browser cookie to bookmark a page

Here's an updated example that uses the newer localStorage API instead of cookies to store the bookmarked page:

  function setBookmark() {
    // Save the current page URL to localStorage
    localStorage.setItem("bookmark", window.location.href);
    alert("Page bookmarked!");

  // Check if the bookmark is saved in localStorage, and display a message to the user
  var bookmark = localStorage.getItem("bookmark");
  if (bookmark) {
    alert("You have bookmarked this page: " + bookmark);

<a href="#" onclick="setBookmark()">Bookmark this page</a>

In this example, we use the localStorage API to save the bookmarked page URL instead of using cookies. The localStorage API provides a simple way to store data on the user's browser that persists even after they close the browser window.

We define a setBookmark() function that saves the current page URL to localStorage and displays an alert to confirm that the page has been bookmarked. We also check if the bookmark is already saved in localStorage when the page loads, and display a message to the user if it is.

The link to bookmark the page calls the setBookmark() function when clicked.

Note that this example uses the localStorage API, which is supported by most modern browsers. However, if you need to support older browsers, you may need to use a polyfill or fallback approach that uses cookies or other storage mechanisms.

Related Articles

- All From ChatGPT