Last active
June 22, 2017 19:37
-
-
Save birm/d10e1abb2b80177b4c229e85009c418f to your computer and use it in GitHub Desktop.
Url Variable Encoding and Decoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<h1>Get link from variables</h1> | |
<form id="vars"> | |
<label for="x">X:</label> | |
<input type="text" id="x"></input> | |
<label for="y">Y:</label> | |
<input type="text" id="y"></input> | |
<label for="z">Zoom:</label> | |
<input type="text" id="z"></input> | |
<button type="button" onClick="enc_url()">Encode</button> | |
</form> | |
Encoded: | |
<div id="url"></div> | |
<script> | |
function enc_url() { | |
var xi = document.getElementById("x").value; | |
var yi = document.getElementById("y").value; | |
var zi = document.getElementById("z").value; | |
var l = encodeURIComponent(btoa(JSON.stringify({ | |
"x": xi, | |
"y": yi, | |
"z": zi | |
}))); | |
document.getElementById("url").innerHTML = l; | |
window.history.pushState("hi", "Encoded", "?state=" + l); | |
} | |
function dec_url() { | |
//TODO some error handling | |
// handle improper encoding gracefully | |
// handle missing field in json gracefully | |
var matches = /state=([^&#=]*)/.exec(window.location.search); | |
if (matches.length) { | |
var xi = matches[1]; | |
var l = atob(decodeURIComponent(xi)); | |
window.history.pushState("hi", "Encoded", "?state=" + xi); | |
var ll = JSON.parse(l); | |
if ("x" in ll && "y" in ll && "z" in ll) { | |
document.getElementById("x").value = ll.x; | |
document.getElementById("y").value = ll.y; | |
document.getElementById("z").value = ll.z; | |
document.getElementById("url").innerHTML = xi; | |
} else { | |
document.getElementById("url").innerHTML = "properties missing"; | |
} | |
} | |
} | |
dec_url(); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment