Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML5 hisotry API exercises
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>HTML5 history API exercise</title>
</head>
<script>
/*
HTML5 history API exercise 1.
reference:
https://developer.mozilla.org/ja/docs/Web/Guide/DOM/Manipulating_the_browser_history
http://breaktimes.hatenablog.com/entry/history-api
http://myakura.github.io/dih5ja/history.html
http://uhyohyo.net/javascript/12_3.html
http://nacika.com/entry/2013/01/18/003325/
http://www.webcyou.com/?p=4329
*/
function updateView(newState) {
document.getElementById("k1").innerHTML = newState.k1;
document.getElementById("k2").innerHTML = newState.k2;
}
function onPopState(event) {
if(event.state) {
console.log(event.state);
updateView(event.state);
} else {
console.log("state = empty");
}
}
function pushState1() {
var newState = {k1:100, k2:"abc"};
history.pushState(newState, null, "#state-1")
updateView(newState);
}
function pushState2() {
var newState = {k1:200, k2:"def"};
history.pushState(newState, null, "#state-2")
updateView(newState);
}
window.addEventListener("popstate", onPopState);
function onLoad() {
var initState = {k1:0, k2:"initialized"};
history.replaceState(initState, null);
updateView(initState);
}
</script>
<body onload="onLoad();">
<input type="button" value="pushState1()" onclick="pushState1();">
<input type="button" value="pushState2()" onclick="pushState2();">
<hr>
<input type="button" value="history.back()" onclick="history.back();">
<input type="button" value="history.forward()" onclick="history.forward();">
<hr>
<div id="k1"></div>
<div id="k2"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment