I’m looking for a way to store a few javascript variables in my URL’s hash. My aim is to allow users to restore a particular state of a web application using a bookmark.
It occurred to me that one approach might use JSON serialization. I.e., I’d store my variables like this
var params = { var1: window.val1, var2: window.val2 }
window.location.hash = JSON.stringify(params)
and recover them like this
var paramStr = window.location.hash.substring(1) // substring removes the initial "#"
var params = JSON.parse(paramStr)
window.var1 = params.var1
window.var2 = params.var2
This seems like the simplest and most concise technique for doing what I want. It’s easy for me to understand, and it uses fewer lines of code, than, for example, this popular SO suggestion. However, it also feels insecure. A malicious user would be able to write arbitrary code into the url, and my app would execute it. This seems dangerous, but I’m pretty new to web programming and so I don’t know how big a deal this is.
Is the technique I’ve outlined above for storing variables in window.location.hash safe to use? If not, why not? What’s the worst that could happen?
Yes, it is safe to parse arbitrary data. A JSON parser does not execute any code that does something different from defining an Object/Array/String/Number. Native ones don’t even use
evalat all (and non-native ones validate the JSON data before usingeval).It is also safe to assign it to predefined (global) variables assuming your code doesn’t do “bad” stuff with those variables.
However, it’s not necessarily safe to assign it to arbitrary global variables. While JSON can’t contain functions you don’t want anyone to be able to overwrite any globals.