跳至主要內容

微信常见功能

Mr.Chen开发日志微信项目总结大约 3 分钟约 955 字

1.重定向落地页获取 code

<script>
import querystring from 'querystring'
export default {
  methods(){
    // 查询协议+域名
		getRedirectUri() {
			let href = window.location.href
			let search = window.location.search
			return href.replace(search, '')
		}
    redirectWx(){
      	const redirect_uri = this.getRedirectUri()
        let params = {
          appid: '', //微信公众号id
          // redirect_uri: encodeURIComponent(redirect_uri),
          redirect_uri: redirect_uri,
          response_type: 'code',
          scope: 'snsapi_userinfo',
          state:'', //自定义参数
          forcePopup: true,
          forceSnapShot: true
        }
        params = querystring.stringify(params)
        this.redirectWxUrl = `${wxUrl}?${params}#wechat_redirect`
        window.location.href = this.redirectWxUrl
    },
   	// 监听浏览器刷新
		addEvents() {
			let eventName = 'beforeunload'
			const { gecko, iPhone, iPad } = this.getBrowserVersion()
			if (gecko) {
				eventName = 'unload'
			}
			if (iPhone || iPad) {
				eventName = 'pagehide'
			}
			window.addEventListener(eventName, this.handlerClosePage)
		},
		removeEvents() {
			let eventName = 'beforeunload'
			const { gecko, iPhone, iPad } = this.getBrowserVersion()
			if (gecko) {
				eventName = 'unload'
			}
			if (iPhone || iPad) {
				eventName = 'pagehide'
			}
			window.removeEventListener(eventName, this.handlerClosePage)
		},
		handlerClosePage() {
			const state = unit.getUrlParam('state')
			const pay = unit.getUrlParam('pay')
			const path = this.$route.path
			if (state && pay === 'sucess' && path === '/wx-surmax-policy') {
				this.closePage()
			}
		},
		// 打开微信公众号主页
		openOfficialAccount() {
				const [appId] = (unit.getUrlParam('state') || '').split(',')
			let biz = mwEnum.appidMap[appId]
			if (!biz || !appId) {
				this.$toast('系统异常,请联系管理员')
				return false
			}
			let params = {
				action: 'home',
				__biz: biz
			}
			params = querystring.stringify(params)
			const url = `https://mp.weixin.qq.com/mp/profile_ext?${params}#wechat_redirect`
			location.replace(url)
		},
    // 重定向url
		redirectUrl(url) {
			if (window.history && window.history.replaceState) {
				window.history.replaceState(null, document.title, url)
				window.history.go(0)
			} else {
				window.location.replace(url)
			}
		},
		// 关闭当前页面
		closePage() {
			const { weixin } = this.getBrowserVersion()
			if (weixin && window.WeixinJSBridge) {
				return window.WeixinJSBridge.call('closeWindow')
			}
			window.close()
		},
		// 浏览器版本
		getBrowserVersion() {
			const u = window.navigator.userAgent
			return {
				trident: u.indexOf('Trident') > -1, //IE内核
				presto: u.indexOf('Presto') > -1, //opera内核
				webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
				gecko:
					(u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1) ||
					u.indexOf('Firefox') !== -1, //火狐内核
				mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
				ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
				android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
				iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
				iPad: u.indexOf('iPad') > -1, //是否iPad
				webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
				weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
				qq: u.match(/\sQQ/i) == ' qq' //是否QQ
			}
		},
    // 初始化页面参数
		setUrlParams(key, value) {
			const url = new URL(window.location)
			const searchParams = new URLSearchParams(url.search)
			searchParams.set(key, value)
			url.search = searchParams.toString()
			window.history.replaceState(null, null, url.toString())
		},
  },
	beforeDestroy() {
		this.removeEvents()
	}
}
</script>

2.安卓机在微信公众号 返回上一页关闭浏览器

<script>
export default {
  created() {
    // location.replace 在安卓机能正常返回 这里对此做兼容
    // 上次离开页面时的参数标识
    const pay = unit.getUrlParam('pay')
    if (['success', 'redirect'].includes(pay)) {
      this.closePage()
      return
    }
  },
  methods: {
    // 关闭当前页面
    closePage() {
      if (typeof window.WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            this.onBridgeReady,
            false
          )
        } else if (document.attachEvent) {
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
        }
      } else {
        this.onBridgeReady()
      }
    },
    onBridgeReady() {
      window.WeixinJSBridge && window.WeixinJSBridge.call('closeWindow')
    }
  }
}
</script>

3. 屏蔽微信浏览器右上角三个点的分享功能

  function onBridgeReady() { //隐藏右上角按钮
  WeixinJSBridge.call('hideOptionMenu');
  }
  if (typeof WeixinJSBridge == "undefined") { //屏蔽分享按钮
  if (document.addEventListener) {
  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  } else if (document.attachEvent) {
  document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
  }
  } else {
  onBridgeReady();
  }
  WeixinJSBridge 的隐藏函数

WeixinJSBridge.call(‘hideToolbar’); //隐藏右下面工具栏
WeixinJSBridge.call(‘showToolbar’); //显示右下面工具栏
WeixinJSBridge.call(‘hideOptionMenu’); //隐藏右上角三个点按钮。
WeixinJSBridge.call(‘showOptionMenu’); //显示右上角三个点按钮。

4. 分享

4.1.分享好友

function sendMessage() {
  WeixinJSBridge.on('menu:share:appmessage', function (argv) {
    WeixinJSBridge.invoke(
      'sendAppMessage',
      {
        appid: '', //appid 设置空就好了。
        'img*url': imgUrl, //分享时所带的图片路径
        img_width: '120', //图片宽度
        img_height: '120', //图片高度
        link: url, //分享附带链接地址
        desc: '我是一个介绍', //分享内容介绍
        title: '标题,再简单不过了。'
      },
      function (res) {
        ;/\*\*\* 回调函数,最好设置为空 \_\*\*/
      }
    )
  })
}

4.2.分享到朋友圈

function sendMessage() {
  WeixinJSBridge.on('menu:share:timeline', function (argv) {
    WeixinJSBridge.invoke(
      'shareTimeline',
      {
        appid: '', //appid 设置空就好了。
        'img*url': imgUrl, //分享时所带的图片路径
        img_width: '120', //图片宽度
        img_height: '120', //图片高度
        link: url, //分享附带链接地址
        desc: '我是一个介绍', //分享内容介绍
        title: '标题,再简单不过了。'
      },
      function (res) {
        ;/\*\*\* 回调函数,最好设置为空 \_\*\*/
      }
    )
  })
}

4.3.分享到微博

function sendMessage() {
  WeixinJSBridge.on('menu:share:weibo', function (argv) {
    WeixinJSBridge.invoke(
      'shareWeibo',
      {
        content: dataForWeixin.title + ' ' + dataForWeixin.url,
        url: dataForWeixin.url
      },
      function (res) {
        /*** 回调函数,最好设置为空 ***/
      }
    )
  })
}

三个分享功能主要是监听的接口不同,

  • 分享给好友(menu:share:appmessage);invoke(‘sendAppMessage’);
  • 分享到朋友圈(menu:share:timeline);invoke(‘shareTimeline’);
  • 分享到微博(menu:share:weibo);invoke(‘shareWeibo’);
上次编辑于: