简体   繁体   中英

Store JavaScript function in cookie?

Is it possible to save a JavaScript function in a cookie? If so, how?

For example, I have user settings for keyboard shortcuts, but the behavior associated with each keystroke could be custom. I was hoping to save these potentially unique and user-specific mappings in a cookie.

I'm currently using Angular 1.4.7 to put the cookie. The data it returns strips out the function.

You shouldn't save the function in a cookie. Instead, you should create an object with all the possible methods the user can execute, and instead store the method name, ie:

var customUserFunctions = {
    someMethod: function() { ... },
    ...
};

And then store "someMethod" in the cookie, and call it with customUserFunctions[variableHoldingSomeMethodString]() .

That being said , this is how you would store the function in a cookie:

// Define your function
var myFunc = function() { console.log("I'm a stored function!"); };
// Turn it into a string
var myFuncString = myFunc.toString();
// Store it in your cookie
document.cookie = myFuncString;
// get your function back
var myCookieFunc = eval(document.cookie);
// call it
myCookieFunc();

Note that this will create a security vulnerability in which an attacker can modify a cookie and your code will execute whatever function(s) they put in there.

No, you can't store a function on a cookie. You could, though, store a reference to the function in an associative array, and store the key in a cookie instead. That way, when the cookie is loaded, use the key to 're-load' the function.

EDIT:

Building on my first answer, the ideal (IMO) solution would be to define a factory which provides the same kind of functionality. That way it can be injected into your modules as required. For example, you could do (rough demo):

app.factory('getUserFunctions', function(){
    return function(keyFromCookie){
      switch (keyFromCookie) {
        case "hello": return function(){
            return "Hello, world!";
        }
        case "goodbye": return function() {
            return "Goodbye, crule world";
        }
        default: return undefined;
      }
    };
});

and call the factory with a token to get a reference to one of the functions you defined:

$scope.fromFactory = getUserFunctions("goodbye");

You can try to use the Function object. Save the content of the function in the cookie than retrieve it, than pass it to the constructor.

var str = "{alert(1)}";
var f = new Function(str);
f();

Fiddle: https://jsfiddle.net/d37qzet6/

But I don't think this is the best approach in this scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM