Mini Program: How to share webview

background

Mini program sharing can only be triggered from the mini program, and the h5 page in the webview cannot directly trigger the mini program sharing.

Since the page to be shared is a page in the webview, and the webview as a container, it is a whole (regardless of the page level inside the webview) as a page of the applet, the page jumps we see are all in In this container.

Therefore, in order to realize page sharing in webview, you need to first pass sharing parameters from the h5 page nested in the webview, and obtain data in the webview page of the applet, and use the data passed by the h5 page as the sharing parameters of the applet.

step

1. h5 sends messages that need to be shared to the mini program through postMessage (the following is the details page of a special section article, after getting the article details, pass it to the mini program)

const ua = window.navigator.userAgent.toLowerCase()
if (ua.indexOf('micromessenger') > -1) {
    
     
  // 判断是否是微信环境
  wx.miniProgram.getEnv(function (res) {
    
    
    if (res.miniprogram) {
    
     // 小程序环境
      const message = {
    
    
        title: '......'
        desc: '.....'
      }
      wx.miniProgram.postMessage({
    
    
        data: {
    
    
          message
        }
      })
    } else {
    
    
      // 非小程序环境下逻辑
      // console.log('不在小程序中')
    }
  })
}

2. The applet terminal processes the parameters passed by the webview. (Note: The applet will only be triggered and receive messages at a specific time (the applet is backed up, the component is destroyed, and shared).)

<web-view
  src="{
    
    { url }}"
  bindmessage="handleWebviewMessage"
  bindload="handleWebviewLoad"
/>

handleWebviewMessage (e) {
    
    
  //h5每次传递的值,都会存在e.$wx.detail.data,根据需要去处理相关值
  const payloadFromWebview = e.$wx.detail.data[e.$wx.detail.data.length - 1]['message']
  this.shareConfig = {
    
     ...this.shareConfig, ...payloadFromWebview }
}

3. Call the sharing method on the mini terminal

onShareAppMessage: function (options) {
    
    
  const webViewUrl = options.webViewUrl
  const orgCode = wx.getStorageSync('orgCode')
  const wxId = wx.getStorageSync('wxId')
  return {
    
    
    title: this.$wepy.shareConfig.title,
    path: '/pages/web-view/tab-web-view?url=' + encodeURIComponent(webViewUrl) + '&orgCode=' + orgCode + '&wxId=' + wxId
   }
 }

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/113448942