Sherzod
Sherzod

Reputation: 5131

How to save JavaScript code in localStorage and execute it later?

I'm wondering if it's even possible to save some js code and pull it up later and execute.

There are basically two problems I'm facing:

Upvotes: 0

Views: 1114

Answers (1)

Alnitak
Alnitak

Reputation: 340055

You should be able to retrieve the text blob and dynamically drop it inside a <script> tag.

This works in the Chrome and MSIE 9 consoles - I didn't try Firefox yet:

var s = document.createElement('script');
s.appendChild(document.createTextNode('alert("hello")'));
document.head.appendChild(s);

As for stringifying the code, it's normally possible to call myFunction.toString() on user supplied functions.

Upvotes: 2

Related Questions