Executing a simple, out of the box function in either sessionStorage or localStorage?

I took a course about “Web Storage” and learned some basic information on localStorage, sessionStorage, setting, getting, removing items and clearing a given web storage. Yet I don’t know how to execute (set?) a ready-to-work function in, say, sessionStorage.

I tried this code:

sessionStorage.setItem("go", function myFunc () {
alert("Hi");
});
myFunc();

Console output is that the function is not defined, and I didn’t find any documentation that will explain how to a similar task.

Hello
I have used sessionstorage really recently

To start up, i’d suggest to use it to just set and retrieve a variable value. Just that.

Then use that variable value to take actions and or run functions.

When you got it working, you can (if needed) shorten the code.

E.g. I have used it to avoid running a page directly (create-order.php). If you open directly the site/create-order.php,

my sessionstorage control variable appears set with value 0 or unset , if these states are found,

it will open a modal without cancel or close actions, it has just one button that will redirect to the main page.

Only from that main page, there is a button that points to “Create Order” and that will set my sessionstorage control variable.

No security in this, just the need to process some POST variables and some pre needed queries in the MySQL DB before to run the create-order.php properly.

SessionStorage looks the perfect tool for this.

I have found the references for my needs at bottom of this page

where the sessionstorage is explained

You can’t directly store a function in web storage as the key, value will be converted into strings.

To recall the data stored you would also need to use either of the following

sessionStorage.getItem('go');
sessionStorage['go'];

However both will only return the following string

"function myFunc() {
alert("Hi");
}"

You could use

eval(sessionStorage['go']);

After which calling myFunc() will work, however in general the eval command is seen as risky as opens up the chance of malicious script being injected into the page.

@scoobycoo I read carefully but I miss this:

Say my Greasemonkey script includes these two segments:

Segment 1:

"function myFunc() {
alert("Hi");
}"

Segment 2:

sessionStorage.getItem('go');
sessionStorage['go'];
eval(sessionStorage['go']);

How do you “bind” or “tie” or “associate” the two code segments so that the function run “sessionly”?

Or the function should actually come between the 1st and 3rd parts so that the final code looks like this:

sessionStorage.getItem('go');
sessionStorage['go'];

"function myFunc() {
alert("Hi");
}"

eval(sessionStorage['go']);

myFunc();

If you brought security up — I plan to run this code on a site which isn’t mine, on a login form with user name and password. Is it still dangerous? Is there no way to do it safe? The webpage is https (if it matters anything, I really don’t know).

I’ve never used Greasemonkey, but as at it’s your own script that you are running then the use of eval is less worrying as you know what the code is doing.

Segment 1 would be what is returned if you just ran sessionStorage[‘go’]

If you wanted to check to see if the sessionStorage contained go before evaluating the code then you could use…

if (!!sessionStorage['go']) { eval(sessionStorage['go']); }

@scoobycoo, I think I’m getting closer to understand you but I still miss why we need the eval and how to properly implement it.

This code for example, alerts “Problem” instead of “Hi”.

This code doesn’t work.

function loginToTreehouse() {
    alert("Hi");
}

sessionStorage.setItem("runLTT", true);
if (sessionStorage.getItem("runLTT") === true) {
    loginToTreehouse();
} else {
    alert("Problem");
}

Would I just need to include eval somehow to make it work once per session?

This worked:

function myFunc() {
    alert("Hi");
}

sessionStorage.setItem("runLTT", true);
if (JSON.parse(sessionStorage.getItem("runLTT")) === true) {
    myFunc();
} else {
    alert("Problem");
}

Eval was only suggested as initial post stated you wanted to save a function in web storage.

Personally I’d avoid using eval, and as you have done just set a flag as you are now doing. One thought is do you really need to parse the data returned in session storage, as you could just apply the following code and save the additional step.


if (sessionStorage.getItem('runLTT') === 'true') {
   myFunc();
} else {
   alert('Problem');
}

Anyway glad you have sorted out your problem.

1 Like

I assume the way you showed above is generally better because it gives the exact same result in less code.

I will explain to you why this code doesn’t work:

function loginToTreehouse() {
    alert("Hi");
}

sessionStorage.setItem("runLTT", true);
if (sessionStorage.getItem("runLTT") === true) {
    loginToTreehouse();
} else {
    alert("Problem");
}

sessionStorage.setItem converts key and value to string.
So you passed boolean true and it’s converted to string "true" and you have used strict comparison operator === to check if stored item is boolean true and of course comparison fails.
This happened:
“true” === true; // return false

To solve this either use == or write boolean true as string "true".
“true” === “true”; // returns true

I highly recommend to always use strict comparison operator (===).

Correct, plus as previously mentioned web storage will convert the set data in to a string.

For reference if you want to store a flag then just use a string to do so, as saves having to do any conversion. However if you want to store an object in web storage then you will need to use JSON.stringify when setting the data and JSON.parse when getting that data back out.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.