Javascript在不同浏览器上的兼容性问题

时间:2018-04-20 12:58:48

标签: javascript

这是我的剧本:

<script type="text/javascript">
    if(localStorage.openpages){
        alert('You have opened this already in a tab!');
        var baseUrl = window.location.origin;
        window.location.href = baseUrl + '/path/to/your/url';
    }else{
        localStorage.openpages = '1';
        window.onbeforeunload = function () {
            localStorage.openpages = '';
        };
    }
</script>

如果您打开相同的标签(同一个网址),您将收到提示消息,然后您将重定向到所需的网址。

这在 Firefox 最新版本中完美无缺。我可以刷新我的第一个标签,但我也没有重定向。

chrome 上,当我访问我的网址(第一个标签页)时,我收到了警告消息,但我没有重定向。我用相同的URL打开另一个选项卡,我收到了警报消息,我被重定向。或者如果我刷新我的第一个标签,我会被重定向。奇怪的 !

IE 11 没有警报,什么都没有,我的脚本被忽略

Safari 上,我不敢尝试:)

有没有办法让该脚本适用于每个浏览器(最新版本)?

谢谢

[UPDATE]

if(localStorage.getItem("openpages")){
    alert('You have opened this already in a tab!');
    var baseUrl = window.location.origin;
    window.location.href = baseUrl + '/index.php/ffmpanel/customer/';
}else{
    localStorage.setItem('openpages', '1');
    window.onbeforeunload = function () {
        localStorage.setItem('openpages', '');
    };
}

使用setItemgetItem,我的行为与描述相同!

1 个答案:

答案 0 :(得分:0)

请试试这个

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

进行测试

我测试

if (localStorage.getItem("openpages") =="1")

而不是

if (localStorage.getItem("openpages"))

因为它可能是真实的

另请注意,location.origin在IE10及更低版本中不可用,并且可能来自file:// protocol

&#13;
&#13;
window.onload = function() {
  if (!storageAvailable("localStorage")) {
    alert("Sorry, localStorage is not available");
    return; 
  }


  if (localStorage.getItem("openpages") == "1") { // stored as string
    alert('You have opened this already in a tab!');
    var baseUrl = window.location.origin;
    window.location.href = baseUrl + '/index.php/ffmpanel/customer/';
  } else {
    localStorage.setItem('openpages', '1');
    window.onbeforeunload = function() {
      localStorage.setItem('openpages', '');
    };
  }

}

function storageAvailable(type) {
  try {
    var storage = window[type],
      x = '__storage_test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return e instanceof DOMException && (
        // everything except Firefox
        e.code === 22 ||
        // Firefox
        e.code === 1014 ||
        // test name field too, because code might not be present
        // everything except Firefox
        e.name === 'QuotaExceededError' ||
        // Firefox
        e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
      // acknowledge QuotaExceededError only if there's something already stored
      storage.length !== 0;
  }
}
&#13;
&#13;
&#13;