Search code examples
javascripthtmlweb-development-serversession-storage

How to use a function as value in Session storage


I want to trigger a function while calling a particular key stored in Session Storage.

I tried the code given below.

sessionStorage.setItem('user', function myfync{alert("Hi")});

But while using the getItem function it is returned to me as a string and the function does not get executed. Is there a workaround to this that I'm missing?


Solution

  • Sessionstorage (and localstorage) only support strings as values.

    This means you have to convert the value into a string before you store it and convert it back after reading it.

    This can be done using String() and Function().

    Example:

    // Write
    const a = function myfunc() {
        alert("Hi");
    };
    sessionStorage.setItem('user', String(a));
    
    // Read
    const b = sessionStorage.getItem('user');
    const c = Function('return ' + b);
    
    //Execute
    c();
    

    Converting a string back to a function is a debatable topic, more info can be found here: Is there a way to create a function from a string with javascript?