赞
踩
最近有个讨论区项目需要补充分享功能,希望可以支持在微信小程序进行分享,讨论区是基于react的h5项目,在小程序中是使用web-view进行承载的
目标是在打开web-view的页面进行分享,那就需要涉及h5和小程序的通讯问题,查看官方文档:
h5代码
注意:我这里是为了方便演示,所以点击按钮才post内容,可以结合自身需求,也可以在加载成功就post数据
import React from "react" import "./WebView.less" const shareData = { title: "测试h5分享", path: "https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html", imageUrl: "https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg", } const WebView = () => { const handleSetShareOptions = () => { // 判断是否再微信小程序环境 const userAgent = navigator.userAgent const isInMiniProgram = userAgent.includes("miniProgram") if (!isInMiniProgram) { return } if (!window["wx"] || !window["wx"].miniProgram) { return } window["wx"].miniProgram.postMessage({ data: shareData, }); } return <div className="web-view-page"> <div className="title">我是h5页面</div> <div className="share-content"> <div className="content"> <div className="content-title">分享内容:</div> <div className="main"> <div className="item">分享标题:{shareData.title}</div> <div className="item">分享路径:微信webView文档:{shareData.path}</div> <div className="item">分享封面图:<img src={shareData.imageUrl} alt='' className='icon-btn' /></div> </div> </div> </div> <div onClick={handleSetShareOptions} className="share-container"> <img src={require("./icon-share.png").default} alt='' className='icon-btn' /> <span>点击设置分享</span> </div> </div> } export default WebView
小程序代码
/pages/newPage/newPage?url=${path}
,<web-view src="{{url}}" bindmessage="handleGetMessage" />
Page({ data: { url: 'http://localhost:3001/64/html5-bbs/web-view', isOverShare: true, shareOptions: { title: "", path: "/pages/index/index", imageUrl: "" }, }, onLoad(options = {}) { if (!options.url) { return } this.setData({ url: options.url}) }, onShareAppMessage() { return this.data.shareOptions }, handleGetMessage(e) { let data = e.detail.data || [] if (!data.length) { return } const { title, path, imageUrl } = data[data.length - 1] this.setData({ shareOptions: { title, path: `/pages/newPage/newPage?url=${path}`, imageUrl, } }) console.log('%c [ ]-157', 'font-size:13px; background:pink; color:#bf2c9f;', this.data.shareOptions) }, })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。