1

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?

Progman
  • 16,827
  • 6
  • 33
  • 48
MissXToTheT
  • 39
  • 1
  • 8
  • @weegee it's not a duplicate since the question is broader than that single step, it's about sessionstorage value format, consequently converting a function to a string *and* creating a function from a string. – seahorsepip Jun 30 '19 at 11:14
  • @seahorsepip the OP knows how to get data from session storage and put in session storage. They don't know how to convert that string to a function _"But while using the getItem function it is returned to me as a string and the function does not get executed"_ It is a clear dupe – weegee Jun 30 '19 at 11:15
  • @geewee It's not, the user tries to put a function in sessionstorage and doesn't understand why he gets a string back from sessionstorage instead of a function. Nowhere in the question is mentioned that he expects a string back from sessionstorage instead of a function. – seahorsepip Jun 30 '19 at 11:17
  • 1
    I was under the assumption that the function should get triggered when getItem is used. – MissXToTheT Jul 01 '19 at 04:26

2 Answers2

1

sessionStorage.setItem will store a String, so technically the answer is no. However, you can use a wrapper for sessionStorage, like:

SessionStorage = {
    setItem: function(key, value) {sessionStorage.setItem(key, value)},
    getItem: function(key) {
        var value = sessionStorage.getItem(key);
        if (value.startsWith("function")) {
            return eval("(" + value + ")()")
        }
        return value;
    }
}

Use it like this:

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

and test it like this:

SessionStorage.getItem('user');

EDIT

I was asked in the comment-section about localStorage, so let's implement a wrapper for that as well:

LocalStorage = {
    setItem: function(key, value) {localStorage.setItem(key, value)},
    getItem: function(key) {
        var value = localStorage.getItem(key);
        if (value.startsWith("function")) {
            return eval("(" + value + ")()")
        }
        return value;
    }
}

Use it like this:

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

and test it like this:

LocalStorage.getItem('user');
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • This works, but cannot use it for the entire session which was the main reason why I wanted to use sessionStorage in the first place – MissXToTheT Jul 01 '19 at 04:21
  • @MissXToTheT it can be used in the entire session. Take a look at the code again: it stores into sessionStorage and loads from there as well. The only thing added here is that it checks for a function and executes if it finds it. Normally, you will need to use SessionStorage instead of sessionStorage in order to achieve this. – Lajos Arpad Jul 02 '19 at 14:03
  • @LajosArpad Why doesn't this work for localStorage? – Verminous Oct 21 '22 at 18:01
  • 1
    @Verminous it should work with `localStorage` as well, if you change the references from `sessionStorage` to `localStorage`. The implementation from my answer was focusing on `sessionStorage` and it created a `SessionStorage` object to deal with it. One can implement the same thing for `localStorage` and name it `LocalStorage`. – Lajos Arpad Oct 22 '22 at 11:26
  • 1
    @Verminous edited my answer to handle `localStorage` as well. Let me know if it's useful. – Lajos Arpad Oct 22 '22 at 11:28
  • @LajosArpad Actually it worked on my experiments here: https://jsfiddle.net/jqzzy/b1tdpezf/105/ But it won't work on Chrome Extension I'm working on apparently because ```eval()``` is considered dangerous and Chrome blocks it. Even though I added ```'wasm-unsafe-eval'``` to the manifest. Is there an alternative to ```eval()``` in your wrapper? – Verminous Oct 22 '22 at 22:27
  • @Verminous Since we are converting text into code, I'm not aware of ways to bypass `eval`. If you provide more information about your specific problem, then there might be a neat solution to that. – Lajos Arpad Oct 23 '22 at 11:33
0

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?

seahorsepip
  • 4,519
  • 1
  • 19
  • 30