Redirect Old Browers Safari Users

2019-08-31 16:25发布

问题:

i'm using this code to redirect safari users...

<script>
    var uagent = navigator.userAgent.toLowerCase();
    if(/safari/.test(uagent) && !/chrome/.test(uagent))
    {
        window.location.href = "http://www.google.com"
    }
</script>

But i need a script to redirect only old safari browsers, someone can please help me?

回答1:

<script type="text/javascript">
    window.onload = function () {
        var uagent = navigator.userAgent.toLowerCase();
        var safari = uagent.match(/safari\/(\S+)/);
        var chrome = uagent.match(/chrome\/(\S+)/);
        var MIN_SAFARI_VERSION = 900;
        if(safari && !chrome) {
            if (parseFloat(safari[1]) < MIN_SAFARI_VERSION) {
                window.location.href = "http://www.google.com"
            }
        }
    }
</script>

The value of safari will be ["safari/(version number)", "(version number)"], so safari[1] will give you the version number as a string. You can then attempt to parse that value as a float (or int) to get the version number, then redirect based on the result.



回答2:

I´ve managed to create a solution to solve the problems on the answer of @evan_schmevan, as it was not working for me.

My solution runs with a different format on uagent.

Hope it helps. Try the snippet

window.onload = function () {
        var uagent = navigator.userAgent.toLowerCase();
        var MIN_SAFARI_VERSION = 11;
        console.log ("Your uagent: ||"+ uagent+"||");

        //First, check if safari appears on the user agent
        var safari = uagent.match(/safari\/(\S+)/);
        
        //Chrome shows SAFARI on its user agent, when used from              //mac, then whe check this to ensure is not chrome
        var chrome = uagent.match(/chrome\/(\S+)/);

        //If safari is detected on uagent
        if(safari.length > 0 && !chrome  ) {
            console.log("Safari detected");
            var version = uagent.match(/version\/([0-9]+)/);
            console.log("Version detected: "+version[1]);
            if(version[1] < MIN_SAFARI_VERSION) {
            console.log ("OOPS!!! Version is lower than min required");
            //window.location.href = "http://www.google.com"
            }
         }
            else if (chrome.length>0)
            {
              console.log("Chrome detected");
            }
        
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body>
<h1> Detect your browser version</h1>
</body>
</html>