bridgeToAppFun.js 1.73 KB
Newer Older
leiqingsong's avatar
leiqingsong committed
1 2
// H5 去调用App的方法
import jsBridge from "./bridge";
xulili's avatar
xulili committed
3
import { getUserInfo } from "@/api/user";
leiqingsong's avatar
leiqingsong committed
4

leiqingsong's avatar
leiqingsong committed
5 6 7 8
function saveUser(data) {
  localStorage.setItem("token", data);
  if (data) {
    getUserInfo().then(res => {
leiqingsong's avatar
leiqingsong committed
9 10 11
      console.log('存用户信息');
      console.log(res);
      console.log('----');
leiqingsong's avatar
leiqingsong committed
12 13 14 15 16 17 18 19
      if (res.code === 0) {
        localStorage.setItem("user", JSON.stringify(res.data));
      }
    })
  } else {
    console.log("调用失败");
  }
}
leiqingsong's avatar
leiqingsong committed
20

leiqingsong's avatar
leiqingsong committed
21 22
// 获取Token
export function getAuthToken() {
leiqingsong's avatar
leiqingsong committed
23
  const userAgent = navigator.userAgent;
leiqingsong's avatar
leiqingsong committed
24
  console.log("ua", userAgent);
leiqingsong's avatar
leiqingsong committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38
  if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1) { // android
    console.log("android, 和安卓交互");
    const token = window.android.getAuthToken();
    console.log('an-token', token);
    return new Promise((resolve, reject) => {
      if (token) {
        saveUser(token);
        resolve(token)
      } else {
        reject('失败')
      }
    })
  } else if (userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { // ios
    console.log("ios");
leiqingsong's avatar
leiqingsong committed
39
    return new Promise((resolve, reject) => {
leiqingsong's avatar
leiqingsong committed
40
      console.log("调用1");
leiqingsong's avatar
leiqingsong committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
      jsBridge.callhandler("getAuthToken", null, data => {
        console.log("调用2");
        localStorage.setItem("token", data);
        console.log("--------------");
        if (data) {
          resolve(data)
          getUserInfo().then(res => {
            if (res.code === 0) {
              localStorage.setItem("user", JSON.stringify(res.data));
            }
          })
        } else {
          console.log("调用失败");
          reject("getAuthToken", data);
        }
      });
    }) 
leiqingsong's avatar
leiqingsong committed
58
  }
leiqingsong's avatar
leiqingsong committed
59
}
leiqingsong's avatar
leiqingsong committed
60 61 62

// 退出
export function logoutToApp() {
leiqingsong's avatar
leiqingsong committed
63
  console.log("退出登录");
leiqingsong's avatar
leiqingsong committed
64 65
  jsBridge.callhandler("logout");
}