zoukankan      html  css  js  c++  java
  • vue hash模式下微信分享,实现参数传递

    背景

    vue项目hash模式下,需要实现微信分享。支持传递多参、无参、以及指定跳转页面、可配置

    实现思路

    由于hash模式 #符号的存在,在不同平台会存在兼容性问题。会导致 分享出去的页面不能跳转到指定页面。所以思路就是 将 页面路径 作为一个参数分享出去(本例 称它为 path参数),打开分享链接后 我们根据path参数 来还原URL,进行重定向。

    主要操作

    1、重定向判断

    在进入项目前,进行url判断:

    1、needRedirect 是否需要重定向:主要看path参数是否存在

    2、返回homeUrl:页面的正常路径。将形如 http://wxh5.gek6.com/bystu/?path=/works&dudu=2&haha=123 转换成 http://wxh5.gek6.com/bystu/#/works?dudu=2&haha=123

    /**
       * 页面重定向-确保页面链接正常
       * 支持多参、无参、指定页面
       * @returns {{needRedirect: *, homeUrl: string}}
       */
      urlResetForWcShare: function () {
        let needRedirect = false, homeUrl = '', searchObReal = {}, searchstr = ''
        let oriUrls = window.location.href.split('?')
        // let baseShareURl = 'http://wxh5.gek6.com/bystu/'
        let baseShareURl = window.location.origin + window.location.pathname
        homeUrl = baseShareURl + `#${config.platform[WECHAT.SHARE_PAGE_PATH]}`
        if (oriUrls.length > 1) {
          let searchUrls = oriUrls[1].split('#')
          let searchUrlReal = searchUrls[0]
          let searchOb = qs.parse(searchUrlReal)
          let {path} = searchOb
          config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach(item => searchObReal[item] = searchOb[item])
          if (config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length)
            searchstr = `?${qs.stringify(searchObReal)}`
          needRedirect = path || config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length !== Object.keys(searchOb).length
          homeUrl += searchstr
        }
        // alert(`页面重定向 baseShareURl: ${window.location.origin + window.location.pathname + `#${config.platform[WECHAT.SHARE_PAGE_PATH]}` + searchstr}`)
        return {
          needRedirect,
          homeUrl,
          search: searchObReal
        }
      }

    2、组装分享出去的链接url

    主要是要携带一些参数:包括path参数,其他参数。

    /**
       * 组装微信分享出去的链接url
       * @param pm // 附带参数
       * @returns {string}
       */
      wrapWcShareLink: function (pm = {}) {
        config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach(item => {
          if (!pm[item])
            throw new Error(`微信分享链接缺少额外参数: ${item}`)
        })
        pm.path = config.platform[WECHAT.SHARE_PAGE_PATH] // 根据path来设置初始页面 当前为根路由
        return window.location.origin + window.location.pathname + '?' + qs.stringify(pm)
      },

    3、实现配置化

    将 分享链接里的携带参数 从配置文件读取

     platform: {
        [WECHAT.SHARE_EXTRA_PM_KEYS]: ['dudu'], // 微信分享-附带参数 键名 集合
        [WECHAT.SHARE_PAGE_PATH]: '/', // 微信分享-指定页面
      },

    使用

    1、根文件 app.vue:

    async created(){
          let urlResetRes = browserUtil.urlResetForWcShare()
          let {needRedirect, homeUrl, search} = urlResetRes
          if (needRedirect) {
            window.location.href = homeUrl
    //        location.reload()
          } else {
            let oldDudu = storage.getLocalStorage(LOCALDATA.WORKS_ID)
            if (!oldDudu || search.dudu != oldDudu)
              storage.setLocalStorage(LOCALDATA.WORKS_ID, search.dudu)
            wx_jssdk.sdk_init(homeUrl);
          }
        }

    2、初始化jssdk。

    async sdk_init(homeUrl){
            // 获取签名数据
            let sign;
            try {
                sign = await getSign(homeUrl); // 访问接口,获取签名数据    
            } catch (err) {
                console.log(err)
                // alert(JSON.stringify(err))
            }
            // console.log('获取签名成功')
            // console.log(sign);
    
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: sign.appid, // 必填,公众号的唯一标识
                timestamp: sign.timestamp, // 必填,生成签名的时间戳
                nonceStr: sign.noncestr, // 必填,生成签名的随机串
                signature: sign.signature, // 必填,签名
                jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone", "onMenuShareWeibo", 'updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表
            });
        }

    额外想法:

    想兼容这样一种情形:页面链接参数有垃圾参数(不属于配置文件里的额外参数)。

    此时 使用 分享链接(无#符号)如 http://wxh5.gek6.com/bystu/?path=/works&dudu=2&haha=123 仍可支持分享。但使用 原始链接(有#)如 http://wxh5.gek6.com/bystu/#/works?dudu=2&haha=123,分享不可用。实质是 window.location.href 在只改变参数的情形下,调用不起作用。

    解决思路是: 在这种情形下 调用 reload()。需要注意兼容原来的功能(同时 location.href,reload 在其他情形会无限循环。所以关键是 判断是否为 此情形。暂未解决!!!遗憾

    优化想法:

    使用伪静态传参,但需要后端的配合(拦截跳转到对应的页面)。链接形如:http://wxh5.gek6.com/bystu/we_2

    尝试代码

    /**
       * 组装微信分享出去的链接url
       * @param pm // 附带参数
       * @returns {string}
       */
      wrapWcShareLink: function (pm = {}) {
        let wePmStr = '', keysSize = config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length
        config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach((item, index) => {
          if (!pm[item])
            throw new Error(`微信分享链接缺少额外参数: ${item}`)
          wePmStr += `we_${item}`
          if (index+1 < keysSize)
            wePmStr += '/'
        })
        return window.location.origin + window.location.pathname + wePmStr
    
      },
      /**
       * 页面重定向-确保页面链接正常
       * 支持多参、无参、指定页面
       * @returns {{needRedirect: boolean, homeUrl: string, search: {}}}
       */
      urlResetForWcShare: function () {
        let needRedirect = false, homeUrl = '', searchObReal = {}, searchstr = ''
        if (location.search)
          needRedirect = true // 二次分享 会自动加search
        let baseShareURl = window.location.origin + window.location.pathname
        let shareFlagIndex = window.location.pathname.indexOf('we_')
        if (shareFlagIndex > 0) {
          needRedirect = true
          baseShareURl = window.location.origin + window.location.pathname.substring(0, shareFlagIndex)
          let weStr = location.pathname.substring( shareFlagIndex)
          weStr = weStr.replace(/we_/g, '')
          let wePms = weStr.split('/')
          if (wePms.length !== config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length)
            throw new Error(`非法链接,参数不匹配`)
          config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach((item, index) => searchObReal[item] = wePms[index])
          if (config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length)
            searchstr = `?${qs.stringify(searchObReal)}`
        }
        //baseShareURl = 'http://wxh5.gek6.com/bystu/'
        homeUrl = baseShareURl + `#${config.platform[WECHAT.SHARE_PAGE_PATH]}` + searchstr
        alert(`页面重定向 homeUrl: ${homeUrl}`)
        return {
          needRedirect,
          homeUrl,
          search: searchObReal
        }
      }
  • 相关阅读:
    js中盒子模型常用的属性你还记得几个?
    编写一个关于浏览器盒子模型的方法
    Javascript中关于作用域和闭包和域解释的面试题
    时间格式转换
    HDU Subset sequence
    bugku never give up
    HDU 2136 Largest prime factor
    HDU 2099 整除的尾数
    杭电acm 2070
    ACM Elevator
  • 原文地址:https://www.cnblogs.com/fan-zha/p/11209177.html
Copyright © 2011-2022 走看看