Can I Store Javascript In A Local Storage Object And Run It?
Solution 1:
While using eval(myScript)
is the most direct approach, I prefer this:
var script = document.createElement('script');
script.src = 'data:text/javascript,' + encodeURI(myScript);
script.onload = function() {
//optional callback
};
document.body.appendChild(script);
This is inserting an actual script tag using a data uri as the source. This way, it will appear under "scripts" on the resources tab of the dev tools. When the script loads, the data uri (your code) will be executed.
Solution 2:
Here are two methods:
Method 1: eval()
eval(localStorage.myCode);
Method 2: the Function
constructor
newFunction(localStorage.myCode)();
Here are the jsfiddle demos showing that they all work:
Method 1: http://jsfiddle.net/markasoftware/3BkAV/
Method 2: http://jsfiddle.net/markasoftware/j6JAz/
Solution 3:
You just need to use the eval function of JavaScript.
You can end up writing something like the following:
localStorage.myCode = "alert('just a test')";
eval(localStorage.myCode);
You can check if your code is stored like this:
if (!localStorage.myCode) {
// local storage code not exists, load from somewhere else
} else {
// perform the eval using the code from local storage
}
I tested this code in Chrome and works. The only problem I see is that you are forcing your users to use only browsers that support local storage.
Here is the browser support:
- IE 8+
- FireFox 3.5+
- Safari 4+
- Chrome 4+
- Opera 10.5+
Post a Comment for "Can I Store Javascript In A Local Storage Object And Run It?"