H5和Android ios交互

1. 判斷手機是安卓或者ios方法

1.1 添加判斷機型方法(適用於Android和ios調用方法不一樣)

// checkDeciveTyoe.js
function checkDevice() {
  // js判斷是否是蘋果設備
  function checkIsAppleDevice() {
      var u = navigator.userAgent,
          app = navigator.appVersion;
      var ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      var iPad = u.indexOf("iPad") > -1;
      var iPhone = u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1;
      if (ios || iPad || iPhone) {
          return true;
      } else {
          return false;
      }
  }
  //js判斷是否爲Android設備
  function checkIsAndroidDevice() {
      var u = navigator.userAgent;
      if (u.indexOf("Android") > -1 || u.indexOf("Adr") > -1) {
          return true;
      } else {
          return false;
      }
  }

  if (checkIsAppleDevice()) {
      return "ios";
  } else {
      return "Android";
  }
}
export default checkDevice;

1.2 頁面中使用(vue)

// 引入檢測機型方法
import checkDevice from "@/utils/checkDeviceType";
export default{
	data: { 
		phone: '',
		userInfo : {},
	};
	created(){
		this.phone = checkDevice();
		window.getAppUser = this.getAppUser // 接收ios返回的數據
	},
	methods: {
	   handleQuit () {
  	   	 if (this.phone == "Android") {
      		 // 調用安卓的方法
      		 window.android.goToAppHome();
     	 } else {
      		 // 調用ios方法
      	  window.webkit &&
          window.webkit.messageHandlers &&
          window.webkit.messageHandlers.closeWebView &&
          window.webkit.messageHandlers.closeWebView.postMessage &&
          window.webkit.messageHandlers.closeWebView.postMessage(null);
          }
      	},
      	getAppUser (str) { // ios 接受用戶基本信息
      		this.userInfo = JSON.parse(str) // 原生返回的是JSON格式 需要轉成對象
    	},
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章