javascript – Onclick Sets a Cookie For a Page-ThrowExceptions

Exception or error:

I Have this button on my site which opens new page on click, so i was trying to set a unique cookie for every users who click on it and access the new page , if someone try to access the new page directly by url than they should see a sample text and redirect automatically to the button page. How can i do that?

<div class="button">
 <a href="/" target="_blank">CLICK HERE TO GET THIS..!</a>
How to solve:


<div class="button">
     <a href="" onclick="what_i_want()" id="the_button" target="_blank">CLICK HERE TO 
     GET THIS..!</a>

JS :

function what_i_want()
    var cookie_name=Math.floor(Math.random() * 1000000) + 1;  //random name for example;
    var cookie_value=" any value";  // << you also can get value from function >> what_i_want(par,par2,par,3);
    document.cookie = cookie_name +'='+ cookie_value;


Even without any sort of database, you can use the local storage built into a web browser to save items. Set the app as your “new tab” page in your browser and the to-dos will persist on your local computer as long as you don’t clear the cache.

Previously, cookies were the only option for remembering this type of local, temporary data. Local storage has a significantly higher storage limit (5MB vs 4KB) and doesn’t get sent with every HTTP request, so it can be a better option for client-side storage.

Here is an overview of localStorage methods.

Method              Description

setItem()       Add key and value to local storage
getItem()       Retrieve a value by the key
removeItem()    Remove an item by key
clear()         Clear all storage

Try it:

localStorage.setItem('key', 'value');

Now if you test localStorage in the console again, you’ll find your new key and value.

Storage {key: "value", length: 1}

More info on how to use localStorage you can find Here

Leave a Reply

Your email address will not be published. Required fields are marked *