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?