H5调用IOS和安卓的方法

Tom最好的朋友是Jerry / 2024-02-23 / 原文

虽然很简单但还是做个记录

 

const u = navigator.userAgent
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端

// 调用原生方法返回
export const onReturn = () => {
  try {
    if (isAndroid) {
      window.nativeObject?.close()
    }
    else if (isiOS) {
      window.webkit?.messageHandlers?.close?.postMessage(null);
    }
  } catch (error:any) {
    console.log(error)
  }
}

  window.nativeObject?.close() ,这是安卓那边指定的方法,像下图这种就是window.badao.jsCallAndroid()

 

   ios也是固定window.webkit?.messageHandlers?.方法名?.postMessage(null);  null是传参部分,如果不传参切记填null,否则可能不生效。