百度判断手机终端并自动跳转uaredirect.js代码及使用实例

function uaredirect(f) {
    try {
        if (document.getElementById("bdmark") != null) {
            return
        }
        var b = false;
        if (arguments[1]) {
            var e = window.location.host;
            var a = window.location.href;
            if (isSubdomain(arguments[1], e) == 1) {
                f = f + "/#m/" + a;
                b = true
            } else {
                if (isSubdomain(arguments[1], e) == 2) {
                    f = f + "/#m/" + a;
                    b = true
                } else {
                    f = a;
                    b = false
                }
            }
        } else {
            b = true
        }
        if (b) {
            var c = window.location.hash;
            if (!c.match("fromapp")) {
                if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))) {
                    location.replace(f)
                }
            }
        }
    } catch(d) {}
}
function isSubdomain(c, d) {
    this.getdomain = function(f) {
        var e = f.indexOf("://");
        if (e > 0) {
            var h = f.substr(e + 3)
        } else {
            var h = f
        }
        var g = /^www./;
        if (g.test(h)) {
            h = h.substr(4)
        }
        return h
    };
    if (c == d) {
        return 1
    } else {
        var c = this.getdomain(c);
        var b = this.getdomain(d);
        if (c == b) {
            return 1
        } else {
            c = c.replace(".", "\.");
            var a = new RegExp("\." + c + "$");
            if (b.match(a)) {
                return 2
            } else {
                return 0
            }
        }
    }
};

  

使用方法:

保存以上代码为uaredirect.js,将这个JS文件的引用最好放到网站的title下,不要放在最后或者其他部位,这样做是因为会先加载uaredirect.js后跳转,这样做会很快,如果先加载其他的JS或者CSS的话,会先加载它们再跳转,这样跳转速度就会很慢了。加载的话,只需要一段代码就OK了

引用代码:

<script src="你的js存放目录/uaredirect.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("http://m.haishiit.com","http://www.haishiit.com");</script>

说明:http://m.haishiit.com 是手机版的网站, http://www.haishiit.com 是电脑版的网站。

转载至:https://www.cnblogs.com/yeyublog/p/6705072.html