Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Store function in localstorage

Is this possible to insert to localstorage or is there other way to store this?

$('#pass_to_score').on('click',function(){

var compressed = function(){
    $('.whole_wrap_of_editcriteria').css('display','none');
    $('#wrappler').css('display','block');
    $('#li_addcriteria').css('display','none');
    $('#li_menu1').addClass('active');
    $('#home').removeClass('active');
    $('#menu1').addClass('active');
    $('#title_panel').html('Edit criteria scoring');
}
compressed();
localStorage.setItem('compressed', compressed());
//i also try set as JSON.stringify but its undefined

});
like image 472
Raffy T Lawrence Avatar asked Aug 12 '16 21:08

Raffy T Lawrence


People also ask

Can we store a function in localStorage?

If you have the function encoded in JavaScript, there would be no need to restore it ever from localStorage , as you already have it available. You cannot JSON encode a function. You could save the source code of the function, and upon retrieval apply eval to it.

Can JavaScript access local storage?

There are four basic JavaScript methods you can use to access and work with localStorage: setItem() - takes a key-value pair and adds it to localStorage. getItem() - takes a key and returns the corresponding value. removeItem() - takes a key and removes the corresponding key-value pair.

What can be stored in localStorage?

LocalStorage is a key/value datastore that's available on a user's browser. Like cookies, LocalStorage can only store string data for its keys and values. The datastore is only accessible to JavaScript within that domain.

What is local storage in JavaScript?

In this Javascript Local storage example we will cover how to store and retrieve data from local storage. What is local storage? Local storage properties allows user to store data in key value pairs in the web browser.

How to store data in local storage using HTML?

Create simple html file which contains a input fields to enter key and values and one button to save the data. How to store data in Local Storage? To store data on Local Storage browser we need to use localStorage object. To store the each data item we need to pass key and value to the setItem () method. How to fetch data from Local Storage?

Where are the keys and values stored in localStorage?

The keys and the values are always in the UTF-16 DOM String format that is stored within localStorage. The storage is the origin (domain) bounded. The data will not get deleted even if the browser is closed or even OS reboot and will be available until we manually clear the Local Storage of our Browser.

What is the use of localStorage?

The localStorage is the read-only property of the window interface. Data is stored as key-value pair and the keys are unique. The keys and the values are always in the UTF-16 DOM String format that is stored within localStorage. The storage is the origin (domain) bounded.


2 Answers

I don't know why you'd want that, I would not recommend it, but you can do it using toString.

Store it:

var myFunc = function (){
  alert('Hello world!');
};

// Store it as a String
localStorage.setItem('compressedFunc', myFunc.toString());

Later, retrieve it:

var compressedFunc = localStorage.getItem('compressedFunc');

// Convert the String back to a function
var myFunc = eval('(' + compressedFunc + ')');

// Use it
myFunc();
like image 197
blex Avatar answered Nov 15 '22 17:11

blex


If you have the function encoded in JavaScript, there would be no need to restore it ever from localStorage, as you already have it available.

You cannot JSON encode a function. You could save the source code of the function, and upon retrieval apply eval to it. But as all know, this has certain risks, captured in the phrase "eval is evil".

You could limit that risk a bit, if you would invent an object structure that closely describes what the function should do. In your case, every statement in the function is a method applied to a jQuery selector. This you could represent with the following object:

var compressed = [
    { selector: '.whole_wrap_of_editcriteria', method: 'css',         args: ['display', 'none'] },
    { selector: '#wrappler',                   method: 'css',         args: ['display', 'none'] },
    { selector: '#li_addcriteria',             method: 'css',         args: ['display','none'] },
    { selector: '#li_menu1',                   method: 'addClass',    args: ['active'] },
    { selector: '#home',                       method: 'removeClass', args: ['active'] },
    { selector: '#menu1',                      method: 'addClass',    args: ['active'] },
    { selector: '#title_panel',                method: 'html',        args: ['Edit criteria scoring'] }
];

Then your actual function, could take that object as its input, and process it, resulting in the same effect:

var applyInstructions = function(instructions) {
    instructions.forEach( cmd => $(cmd.selector)[cmd.method](...cmd.args) );
}

Now, when you want to save this knowledge to localStorage, you only need to store the above constructed object, like so:

// save to localStorage:
localStorage.setItem('compressed', JSON.stringify(compressed));

And after retrieving it, you would execute the generic function on it:

// get from localStorage:
applyInstructions(JSON.parse(localStorage.getItem('compressed')));

This is similar to using eval, but it has the advantage that you can put limits to what can be executed (in applyInstructions). You could for instance check that the method attribute should only be one of the values css, addClass, removeClass, and html, although that last one could be a dangerous one to keep. text would be a better alternative, if possible.

Here is how that safer applyInstructions could look like:

var applyInstructions = function(instructions) {
    if (instructions.some( 
            cmd => ['css','addClass','removeClass','textContent'].indexOf(cmd.method)==-1)) {
        throw "Invalid instructions object";
    }
    instructions.forEach( cmd => $(cmd.selector)[cmd.method](...cmd.args) );
}
like image 27
trincot Avatar answered Nov 15 '22 17:11

trincot