#navi_header|技術| WebStorageのサンプルとメモ。 参考: - Web Storage -- http://dev.w3.org/html5/webstorage/ - LocalStorageがおもいのほか便利すぎたのでまとめ - ブックマクロ開発に -- http://d.hatena.ne.jp/takuya_1st/20110815/1313415947 Firefox 6.0, Chrome 13, IE9 にて確認。 #more|| * サンプル t_webstorage.js: #pre||> function getkey_l() { alert(localStorage.testkey); } function setkey_l() { localStorage.testkey = document.forms[0].testkey.value; } function getkey_s() { alert(sessionStorage.testkey); } function setkey_s() { sessionStorage.testkey = document.forms[0].testkey.value; } ||< t_webstorage1.html: #pre||> Web Storage Example 1

Value:

Local Storage

Session Storage

||< 以下のようにアクセスできるようにしておく。 http://foo.example.com/html5/t_webstorage.js http://foo.example.com/html5/t_webstorage1.html 複数TABまたはウインドウで開いてみると、localStorageの方はget/setが連動しているのに対し、sessionStorageの方はTAB/ウインドウ毎に独立していることが確認できる。またTAB/ウインドウを開き直したりすると、sessionStorageはその都度値がクリアされていることが確認できる。 WebStorageはSameOriginポリシーに基づく。 そのため、hostsファイルを編集するなどして http://bar.example.com/html5/t_webstorage1.html などからアクセスしてみると、きちんと独立してget/set出来ていることを確認できる。 もちろん、 とした t_webstorage2.html を用意して foo.example.com からアクセスしてみても正常に動作する。JavaScriptファイルの場所ではなく、実際に動作するホストに基づく。 * iframeと別ドメイン SameOriginポリシーに基づくということは、iframeで別ドメインを読み込んだ時、DOMオブジェクトへのアクセスがブロックされることが期待される。 http://bar.example.com/html5/t_webstorage3.html としてアクセスできるHTMLを以下のように用意してみる。 #pre||> Web Storage Example 1

Value:

Local Storage

Session Storage



Value:

Local Storage

Session Storage

||< 下半分のFormとJavaScriptは、iframe内の別ドメインのWebStorageオブジェクトを参照している。 Chrome13: Unsafe JavaScript attempt to access frame with URL http://foo.example.com/html5/t_webstorage1.html from frame with URL http://localhost/html5/t_webstorage3.html. Domains, protocols and ports must match. t_webstorage3.html:29 Uncaught TypeError: Cannot set property 'testkey' of undefined Firefox 6.0: Error: Permission denied to access property 'localStorage' Source File: http://localhost/html5/t_webstorage3.html Line: 25 IE9: SCRIPT5: アクセスが拒否されました。 以上のように、予想通りiframe別ドメイン間でのアクセスがブロックされることが確認できた。 #navi_footer|技術|