kuboon
9/9/2015 - 6:39 AM

Avoid the behavior that Edge browser does not persist checkbox and radio state on history.back()

Avoid the behavior that Edge browser does not persist checkbox and radio state on history.back()

history.back() 時の Edge ブラウザの特徴的挙動

  • checkbox と radio の checked 属性が保持されない
    • 保持されないどころか、 [input type='radio' checked] が back() で戻ってくると選択されてない

history.back() 時のブラウザ一般の挙動 (たぶん)

  • dataset ( jQueryでいうところの $elem.data('hoge') でアクセスできるやつ ) は一切保持されない。
  • Javascript で hidden の input 要素を生成した場合、要素自体保持されない。
  • あらかじめ hidden 要素が html に存在しており、 そこに Javascript で value を指定したものは、 DOMContentLoaded 後にその値を読めるようになる。
<input type="hidden" id="edge_back_data_store" />
<script type="text/javascript">
+function(){
  var edge_ver = function(){
    var match = navigator.userAgent.match(new RegExp('Edge/(.+)'));
    return match ? parseFloat(match[1]) : 999
  }
  if(12.1024 < edge_ver()) return;

  var data_store = document.getElementById('edge_back_data_store');
  if(!data_store) return;

  var data_hash,
  document_onload = function(){
    var targets = document.querySelectorAll('input[type=radio], input[type=checkbox]');
    data_hash = data_store.value ? JSON.parse(data_store.value) : {};
    Array.prototype.forEach.call(targets, function(node) {
      var val = data_hash[node.name];
      if(val){
        node.checked = (node.type == 'radio' ? (node.value == val) : ('true' == val));
      }
      node.addEventListener("click", elem_onclick);
    });
  },
  elem_onclick = function(){
    data_hash[this.name] = (this.type == 'radio' ? this.value : this.checked)
    data_store.value = JSON.stringify(data_hash);
  };
  document.addEventListener('DOMContentLoaded', document_onload);
}();
</script>