app常用方法

833 阅读3分钟

都是集成用于sdk的干货

  • 浏览器版本
  • 判断移动终端浏览器版本信息
  • 判断设备
  • 获取链接中参数列表
  • 百度地图定位
  • 是否在范围内
  • 请求打开协议和链接
  • 打开App
  • app访问
  1. 浏览器版本:
var getUserAgent = function() {
      var appName = navigator.appName; //浏览器的正式名称
      var appVersion = navigator.appVersion; //浏览器的版本号
      var cookieEnabled = navigator.cookieEnabled; // 返回用户浏览器是否启用了cookie
      var cpuClass = navigator.cpuClass; //返回用户计算机的cpu的型号,通常intel芯片返回"x86"(火狐没有)

      var mimeTypes = navigator.mimeTypes; // 浏览器支持的所有MIME类型的数组
      var platform = navigator.platform; // 浏览器正在运行的操作系统平台,包括Win16(windows3.x)  
      //   Win32(windows98,Me,NT,2000,xp),Mac68K(Macintosh 680x0)
      //     和MacPPC(Macintosh PowerPC)
      var plugins = navigator.plugins; //  安装在浏览器上的所有插件的数组
      var userLanguage = navigator.userLanguage; // 用户在自己的操作系统上设置的语言(火狐没有)
      var userAgent = navigator.userAgent; //包含以下属性中所有或一部分的字符串:appCodeName,appName,appVersion,language,platform
      var systemLanguage = navigator.systemLanguage; // 用户操作系统支持的默认语言(火狐没有)
      
      return {
          '浏览器的正式名称': appName,
          '浏览器的版本号': appVersion,
          '返回用户浏览器是否启用了cookie': cookieEnabled,
          '用户计算机的cpu的型号': cpuClass,
          '浏览器支持的所有MIME类型的数组': mimeTypes,
          '浏览器正在运行的操作系统平台': platform,
          '安装在浏览器上的所有插件的数组': plugins,
          '用户在自己的操作系统上设置的语言(火狐没有)': userLanguage,
          'userAgent': userAgent,
          '用户操作系统支持的默认语言(火狐没有)': systemLanguage
      }
  }
  1. 判断移动终端浏览器版本信息
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {         //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
            weixin: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger" ? true : false//判断是否为微信
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
  }
  1. 判断设备
var getDevice = function ($) {
    var device = {};
    var ua = navigator.userAgent;

    var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
    var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
    var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
    var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);

    device.ios = device.android = device.iphone = device.ipad = device.androidChrome = false;

    // Android
    if (android) {
        device.os = 'android';
        device.osVersion = android[2];
        device.android = true;
        device.androidChrome = ua.toLowerCase().indexOf('chrome') >= 0;
    }
    if (ipad || iphone || ipod) {
        device.os = 'ios';
        device.ios = true;
    }
    // iOS
    if (iphone && !ipod) {
        device.osVersion = iphone[2].replace(/_/g, '.');
        device.iphone = true;
    }
    if (ipad) {
        device.osVersion = ipad[2].replace(/_/g, '.');
        device.ipad = true;
    }
    if (ipod) {
        device.osVersion = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
        device.iphone = true;
    }
    // iOS 8+ changed UA
    if (device.ios && device.osVersion && ua.indexOf('Version/') >= 0) {
        if (device.osVersion.split('.')[0] === '10') {
            device.osVersion = ua.toLowerCase().split('version/')[1].split(' ')[0];
        }
    }

    // Webview
    device.webView = (iphone || ipad || ipod) && ua.match(/.*AppleWebKit(?!.*Safari)/i);

    // Minimal UI
    if (device.os && device.os === 'ios') {
        var osVersionArr = device.osVersion.split('.');
        device.minimalUi = !device.webView &&
            (ipod || iphone) &&
            (osVersionArr[0] * 1 === 7 ? osVersionArr[1] * 1 >= 1 : osVersionArr[0] * 1 > 7) &&
            $('meta[name="viewport"]').length > 0 && $('meta[name="viewport"]').attr('content').indexOf('minimal-ui') >= 0;
    }

    // Check for status bar and fullscreen app mode
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    device.statusBar = false;
    if (device.webView && (windowWidth * windowHeight === screen.width * screen.height)) {
        device.statusBar = true;
    }
    else {
        device.statusBar = false;
    }

    // Classes
    var classNames = [];

    // Pixel Ratio
    device.pixelRatio = window.devicePixelRatio || 1;
    classNames.push('pixel-ratio-' + Math.floor(device.pixelRatio));
    if (device.pixelRatio >= 2) {
        classNames.push('retina');
    }

    // OS classes
    if (device.os) {
        classNames.push(device.os, device.os + '-' + device.osVersion.split('.')[0], device.os + '-' + device.osVersion.replace(/\./g, '-'));
        if (device.os === 'ios') {
            var major = parseInt(device.osVersion.split('.')[0], 10);
            for (var i = major - 1; i >= 6; i--) {
                classNames.push('ios-gt-' + i);
            }
        }

    }
    // Status bar classes
    if (device.statusBar) {
        classNames.push('with-statusbar-overlay');
    }
    else {
        $('html').removeClass('with-statusbar-overlay');
    }

    // Add html classes
    if (classNames.length > 0) $('html').addClass(classNames.join(' '));

    // keng...
    device.isWeixin = /MicroMessenger/i.test(ua);

    // keng...
    if(ua.match(/Android/i) || ua.match(/webOS/i) || ua.match(/iPhone/i) || ua.match(/iPad/i) || ua.match(/iPod/i) || ua.match(/BlackBerry/i) || ua.match(/Windows Phone/i) ){
        device.isMobile = true;
    }else{
        device.isMobile = false;
    }
    $.device = device;
  }
  1. 获取链接中参数列表
var GetRequest = function (url) {
    if (!url || url.indexOf('?') == -1) {
        return {};
    }
    var url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
    var theRequest = new Object();
    var str = decodeURI(url);
    var strs = void 0;
    if (str.indexOf("&") != -1) {
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    } else {
        theRequest[str.split("=")[0]] = decodeURIComponent(str.split("=")[1]);
    }

    return theRequest;
  }
  1. 百度地图定位
var getGeolocation = function (callback){
    if(navigator.geolocation) {
        // 百度地图API功能
        var map = new BMap.Map("container");
        var point = new BMap.Point(116.331398,39.897445);
        map.centerAndZoom(point,12);
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                var mk = new BMap.Marker(r.point);
                map.addOverlay(mk);
                map.panTo(r.point);
                callback(r.point);
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true});
    }
  }
  1. 是否在范围内
var isInCircle = function (point,rules){
    var act_point = new BMap.Point(rules.longitude,rules.latitude);
    var circle = new BMap.Circle(act_point,rules.range,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3});
    return BMapLib.GeoUtils.isInCircle(point,circle);
  }
  1. 请求打开协议和链接
var openAPPScheme = function (postdata,callback){
    $.ajax({
        type: 'GET',
        url: '/api/activity/package-url/'+postdata.act_id,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (data) {
            if(data.code==200){
                $.toast(data.message);
            }
            callback(data);
        },
        error: function(data){
            console.log(data);
        }
    });
  }
  1. 打开App
var openApp = function (packageIOS,packageAndroid) {
    var ua = window.navigator.userAgent;
    var isWechat = /MicroMessenger/i.test(ua);
    var isQQ = /qq/i.test(ua.toLowerCase());
    var isIOS = ua.match(/(iPhone|iPod|iPad);?/i);
    var isAndroid = ua.match(/android/i);
    openAPPScheme({
        act_id: window.parameter.act_id,
    },function(data){
      var open_url = '',act_url=location.origin+location.pathname;
      if (isIOS) {//ios app协议
          if(!data.data.ios_url && !packageIOS){
              window.location.href = data.data.app_url;
          }else{
              open_url = data.data.ios_url + '?tag=2&type=4&url='
                  + encodeURIComponent(location.href);
              if(packageIOS){
                  open_url = packageIOS + '?tag=2&type=4&url='
                      + encodeURIComponent(location.href);
              }    
              try {
                  window.location.href = open_url;
              } catch (error) {
                  window.location.href = '/act/common/download.html?group_id='+window.group_id+'&act_url=' + act_url + '&act_id=' + window.parameter.act_id;
              }
              window.setTimeout(function () {
                  window.location.href = '/act/common/download.html?group_id='+window.group_id+'&act_url=' + act_url + '&act_id=' + window.parameter.act_id;
              }, 2000);
          }
      }else if (isAndroid) {//android app协议
          if(!data.data.android_url && ! packageAndroid){
              window.location.href = data.data.app_url;
          }else{
              open_url = data.data.android_url + 'type16?tag=2&url=' + location.href;
              if(packageAndroid){
                  open_url = packageAndroid + 'type16?tag=2&url=' + location.href;
              }
              var ifr = document.createElement('iframe');
              ifr.src = open_url;
              ifr.style.display = 'none';
              document.body.appendChild(ifr);
              window.setTimeout(function () {
                  document.body.removeChild(ifr);
                  window.location.href = '/act/common/download.html?group_id='+window.group_id+'&act_url=' + act_url + '&act_id=' + window.parameter.act_id;
              }, 2000);
          }
      }
    });
  }
  1. app访问
var APPCall = function (responseCallback){
    var u = navigator.userAgent,
        app = navigator.appVersion;
    if(!window.parameter['mfSign']){
        responseCallback({});
    }else if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
        if(window.android && window.android.morefunObjcGetUserInfo){
            try{
                responseCallback(JSON.parse(window.android.morefunObjcGetUserInfo()));
            }catch(err){
                console.info(err);
                responseCallback({});
            }
        }else{
            responseCallback({});
        }
    }else if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)|| u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1){
        function setupWebViewJavascriptBridge(callback) {
            if (window.WebViewJavascriptBridge) {
                return callback(WebViewJavascriptBridge);
            }
            if (window.WVJBCallbacks) {
                return window.WVJBCallbacks.push(callback);
            }
            window.WVJBCallbacks = [callback];
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'https://__bridge_loaded__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function () {
                document.documentElement.removeChild(WVJBIframe)
            }, 0)
        }

        setupWebViewJavascriptBridge(function (bridge) {
            bridge.callHandler('morefunObjcGetUserInfo', {}, function (response) {
                responseCallback(JSON.parse(response));
            });
        });
    }
  }