uni app 链接打开app 并传参

1,059 阅读1分钟

1、uni app 配置 UrlSchemes

image.png

2、h5页面点击按钮打开app

image.png

此方法为了页面有加载效果引入了layui,如果不需要可以删除layui使用,不影响具体使用。

layui.use(function(){
  let layer = layui.layer
    , $ = layui.$;
  $('.btn').click(function() {
    // 点击按钮触发
    let loadIndex = layer.load(0, {
      shade: [0.2, '#000']
    });
    let u = navigator.userAgent;
    let isWeixin = u.toLowerCase().indexOf('micromessenger') !== -1; // 微信内
    if(isWeixin) {
      layer.close(loadIndex)
      layer.alert('请在浏览器打开')
      return false;
    }
    let search = window.location.search;
    let params = search.split('?')[1] || '';
    const currentTime = new Date().getTime();
    //找工程师要 UrlSchemes
    console.log("cs://" + params)
    // window.location.href = 'cs://url=/pages/index/index&share_id=261&share_type=1'; 
    window.location.href = 'cs://' + params;
    // 启动间隔20ms运行的定时器,并检测累计消耗时间是否超过2000ms,超时则结束
    let _count = 0, timer;
    timer = setInterval(() => {
      _count++;
      const endTime = new Date().getTime() - currentTime;
      
      if (_count >= 200 || endTime > 5000) {
        layer.close(loadIndex)
        clearInterval(timer);
        let hidden = document.hidden || window.document.hidden || window.document.mozHidden || window.document.msHidden || window.document.webkitHidden;
        if (typeof hidden == "undefined" || hidden == false) {
          layer.confirm('您的设备未安装此App,是否前往下载页面?', {icon: 3}, function(){
            window.location.href = ''
          });
          
        }
      }
    }, 20)
  })
  
})

3、uniapp项目App.vue文件中在 onShow 中接受参数

// 第三方传递的参数
let args = plus.runtime.arguments;
// 链接格式
// let args = 'cs://url=/pages/index/index&share_id=261&share_type=1'
if(args) {
  let str = args.split('://')[1] || '';
  if(!str) return;
  // // 参数
  let params = str.split("&").reduce(function (prev, curr, i, arr) {
      let pair = curr.split("=");
      prev[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      return prev;
  }, {});
  // uni.setStorageSync('shareParams', JSON.stringify(params))
      
  let token=uni.getStorageSync('token');
  // 判断用户是否登录
  if(token) {
    uni.reLaunch({
      url: `${params.url}?share_id=${params.share_id}&share_type=${params.share_type}`
    })
  }else {
    uni.showModal({
      title: '提示',
      content: '请您登录后重新点击链接进入'
    })
  }
  
}

写在最后

本次算是笔记分享吧 , 怕下次写这功能时要翻找资料 ,所以就一次性记录一下!