检查javascript中的多个相同选项卡,浏览器问题

时间:2018-04-16 09:24:33

标签: javascript browser tabs

我正在尝试创建一个可以在所有浏览器上运行的脚本,我在firefox上运行它即可。在chrome上,显示第一个打开的选项卡的警报消息,但我没有重定向。它应该是第一次显示。任何的想法 ?一个

我想检查是否多次打开相同的标签页。如果是,则重定向到另一个页面。

<script type="text/javascript">
    // Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';
    // Safari 3.0+ "[object HTMLElementConstructor]"
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;
    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;
    // Chrome 1+
    var isChrome = !!window.chrome && !!window.chrome.webstore;

    //only when an order is created
    var redirectFlag = false;
    if (+localStorage.tabCount > 0) {
        alert('There is already an order tab or window opened! You will be redirected to the customer grid!');
        redirectFlag = true;
    } else {
        localStorage.tabCount = 0;
    }
    localStorage.tabCount = +localStorage.tabCount + 1;
    //works for firefox
    if (isFirefox) {
        window.addEventListener('beforeunload', function (evt) {
            localStorage.tabCount = +localStorage.tabCount - 1;
        });
    }
    //works for edge and ie
    if (isEdge || isIE) {
        window.addEventListener('onpagehide', function (evt) {
            localStorage.tabCount = +localStorage.tabCount - 1;
        });
    }
    //doesn't work
    if (isChrome || isSafari || isOpera) {
        window.addEventListener('onunload', function (evt) {
            localStorage.tabCount = +localStorage.tabCount - 1;
        });
    }
    //redirect user if there are 2 tabs/windows opened
    if (redirectFlag) {
        var baseUrl = window.location.origin;
        window.location.href = baseUrl + '/index.php/customer/';
    }
</script>

0 个答案:

没有答案