微信分享的坑

290 阅读1分钟

微信分享遇到的坑

1、跨越问题

  判断是否在同一个一级域名下边,如果在就直接分享跳转,如果不在同一个一级域名下边,就说明跨域了,需要先跳转到空白页,再跳转到目标地址。
    var host = window.location.host.split('.').slice(-2).join('.');

    if (mylink.indexOf(host) < 0) {
        var mylink = url + '/transfer?url=' + shareUrl;
    }

2、分享地址处理

    分享的地址需要进行编码
    encodeURIComponent(window.location.href.split('#')[0])

3、分享图片的地址

    分享图片的地址前缀必须加上“http”

    var imgUrl = 'http://' + window.location.host + xxx + '/file/download?id=123456' ;

4、编码

function wxConfig(xxx, url) {
  //分享图标
  var imgUrl = 'http://' + window.location.host + xxx + '/file/download?id=123456' ;

  //判断是否在同一个一级域名下边,如果在就直接分享跳转,如果不在同一个一级域名下边,就说明跨域了,需要先跳转到空白页,再跳转到目标地址。

  //比如www.testone.com和www.testtwo.com就不是同一个域名,www.test.wx.testone.com和www.testone.com就是同一个域名,

  //因为test域名是testone.com的三级域名,所以不存在跨域问题
  var host = window.location.host.split('.').slice(-2).join('.');
  if (mylink.indexOf(host) < 0) {
    var mylink = url + '/transfer?url=' + shareUrl;
  }

  $.post(xxx + "/wxsign/signature" + "?url=" +    		
         encodeURIComponent(window.location.href.split('#')[0]), function (data) {
    wx.config({
      // debug: true,       
      debug: false,
      appId: data.appId,
      timestamp: data.timestamp,
      nonceStr: data.noncestr,
      signature: data.signature,
      jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'hideMenuItems']
    })
  })
}