SoFunction
Updated on 2025-04-12

Uniapp WeChat applet webview and h5 data communication code example

Preface

The project is written by Uniapp. Because h5 and app were developed first, the applet was suddenly used, and it was too late to do compatible development. Because the WeChat applet webview loaded h5 because communication must be specially restricted (when a webpage reaches the applet postMessage, a message will be triggered at the following specific times: applet back, component destruction, sharing, and copy link (2.31.1). = { data }, data is an array of postMessage parameters multiple times.), which cannot meet the needs of use, so a specially low communication mechanism is developed. The disadvantage is that there will be a loading transition page during communication.

The business logic is roughly:

1. The WeChat mini program webview accesses the url with parameters of h5, obtains the initial parameters, can carry page parameters or log in token, etc., and accepts the parameters returned by h5 through the reciver.

2. h5 stores the communication logic of the applet through an intermediate html page, and then the cached local data is always obtained through a timer on the h5 page, and different business logics are executed according to the data information.

1. WeChat mini program project

(1) WeChat mini program project

<template>
  <web-view v-if="src" :src="src" bindload="bindload" binderror="binderror"></web-view>
</template>

<script lang="ts">
import { cfg } from '@/cfg'
import Base64 from '@/utils/Base64'

export default {
  data() {
    return {
      src: '',
    }
  },
  onLoad(e: any) {
    let loginA = parseInt()
    ()
    if (loginA) {
      let self = this
      ({
        success(res: any) {
          // Automatic login successfully          (Base64.encode64('loginA,' + ([loginA, , ])))
        },
        fail(res: any) {
          // Automatic login failed          (Base64.encode64('loginAFail,' + ([loginA, ])))
        },
      })
      return
    }

    ()
  },
  methods: {
    msg(msg: any) {
      if (msg) {
         =  + 'static/?uid=' +  + '&msg=' + msg
        //  = '/#/'
        ()
        // Timeout automatically closes        // @ts-ignore
        this['$timer'] = setTimeout(() => {
          ()
        }, 3000)
        return
      }

      ()
    },
    bindload() {
      ('bindload')
      ()
    },
    binderror() {
      ('binderror')
      ()
    },
    navBack() {
      let pages = getCurrentPages()
      if (pages[ - 1].$vm == this) {
        ()
      }

      // @ts-ignore
      let timer = this['$timer']
      if (timer) {
        // @ts-ignore
        delete this['$timer']
        clearTimeout(timer)
      }
    },
  },
}
</script>

<style></style>

(2)

<template>
  <view ></view>
</template>

<script lang="ts">
import { App } from '@/store/app'
import Base64 from '@/utils/Base64'

export default {
  data() {
    return {
      src: '',
    }
  },
  onLoad(e: any) {
    try {
      let msg = 
      if (msg) {
        msg = Base64.decode64(msg)
        let i = (',')
        let key = msg
        let val = ''
        if (i > 0) {
          key = (0, i)
          val = (i + 1)
        }
        // If it is payment for the PC mini program Bridge, it will jump directly to the payment page        // const info = ()
        // if ((info?.deviceType == 'pc' || info?.deviceType == 'PC') && key == 'pay') {
        //   ({
        //     url: `/pages/index/pay?pay=${Base64.encode64(val)}`,
        //   })
        // } else {
        //   ({
        //     complete() {
        //       // setTimeout(() => {
        //       (key, val)
        //       // }, 100)
        //     },
        //   })
        // }
        ({
          complete() {
            // setTimeout(() => {
            (key, val)
            // }, 100)
          },
        })
        return
      }
    } catch (e) {
      (e)
    }

    ()
  },
  methods: {},
}
</script>

<style scoped>
#preloader {
  position: absolute;
  width: 30px;
  height: 30px;
  background: rgba(253, 87, 17, 1);
  border-radius: 50px;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  -webkit-animation: preloader_1 1.5s infinite linear;
  -moz-animation: preloader_1 1.5s infinite linear;
  -ms-animation: preloader_1 1.5s infinite linear;
  animation: preloader_1 1.5s infinite linear;
}
#preloader:after {
  position: absolute;
  width: 50px;
  height: 50px;
  border-top: 10px solid rgba(255, 139, 9, 1);
  border-bottom: 10px solid rgba(255, 139, 9, 1);
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-radius: 50px;
  content: '';
  top: -20px;
  left: -20px;
  -webkit-animation: preloader_1_after 1.5s infinite linear;
  -moz-animation: preloader_1_after 1.5s infinite linear;
  -ms-animation: preloader_1_after 1.5s infinite linear;
  animation: preloader_1_after 1.5s infinite linear;
}

@-webkit-keyframes preloader_1 {
  0% {
    -webkit-transform: rotate(0deg);
  }
  50% {
    -webkit-transform: rotate(180deg);
    background: #ff4f11;
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
@-webkit-keyframes preloader_1_after {
  0% {
    border-top: 10px solid rgba(253, 87, 17, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
  50% {
    border-top: 10px solid rgba(253, 87, 17, 1);
    border-bottom: 10px solid rgba(253, 87, 17, 1);
  }
  100% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
}

@-moz-keyframes preloader_1 {
  0% {
    -moz-transform: rotate(0deg);
  }
  50% {
    -moz-transform: rotate(180deg);
    background: #ff4f11;
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}
@-moz-keyframes preloader_1_after {
  0% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
  50% {
    border-top: 10px solid rgba(253, 87, 17, 1);
    border-bottom: 10px solid rgba(253, 87, 17, 1);
  }
  100% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
}

@-ms-keyframes preloader_1 {
  0% {
    -ms-transform: rotate(0deg);
  }
  50% {
    -ms-transform: rotate(180deg);
    background: #ff4f11;
  }
  100% {
    -ms-transform: rotate(360deg);
  }
}
@-ms-keyframes preloader_1_after {
  0% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
  50% {
    border-top: 10px solid rgba(253, 87, 17, 1);
    border-bottom: 10px solid rgba(253, 87, 17, 1);
  }
  100% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
}

@keyframes preloader_1 {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
    background: #ff4f11;
  }
  100% {
    transform: rotate(360deg);
  }
}
@keyframes preloader_1_after {
  0% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
  50% {
    border-top: 10px solid rgba(253, 87, 17, 1);
    border-bottom: 10px solid rgba(253, 87, 17, 1);
  }
  100% {
    border-top: 10px solid rgba(255, 139, 9, 1);
    border-bottom: 10px solid rgba(255, 139, 9, 1);
  }
}
</style>

(3)

import cfg from '@/cfg'
import Base64 from '@/utils/Base64'

export const App = {
  shareData: {},
  mpPostMsg(key: string, val?: string, redirect: boolean = true) {
    const msg = val ? key + ',' + val : key
    if (redirect) {
      ({ url: '/pages/msg/post?msg=' + Base64.encode64(msg) })
    } else {
      ({ url: '/pages/msg/post?msg=' + Base64.encode64(msg) })
    }
  },
  mpRecievers: {
    userStorageCert(cert: string) {
      ('userCert', cert)
      if (cert) {
        ( + 'userStorageCert', cert)
      }
    },
    shareAppMessage(v: string) {
      let share
      try {
        share = (v)
        if () {
          // Use regular expression to match the string after _i=          const match1 = (/_i=([^&]+)/)
          // If the match is successful, get the matching string          if (match1) {
            const extractedString = match1[1]
             = '/pages/index/index?i=' + extractedString
            (' ', )
          }
        }
      } catch (error) {}

      try {
        if () {
           = (/(w_\d+)|(h_\d+)/g, (match: string) => {
            if (('w_')) {
              return 'w_300'
            } else if (('h_')) {
              return 'h_300'
            }
          })
        }
      } catch (error) {}

      if (share) {
         = share
      }
    },
    pay(v: string) {
      const pay = (v)
       = function () {
        // Notice required        ('pay,1', undefined, false)
      }
      //  = function () {
      //   // Notice required      //   ('pay,1', undefined, false)
      // }
       = function (e: any) {
        ('pay fail ' + (e))
        ({
          title: 'Pay failed',
          icon: 'none',
          duration: 2000,
        })
      }

      // Payment parameters      ((pay))
      const info = ()
      // If it is payment for the PC mini program Bridge, it will be delayed to prevent the payment pop-up window from being displayed      if (info?.deviceType == 'pc' || info?.deviceType == 'PC') {
        ()
        setTimeout(() => {
          ()
          (pay)
        }, 1000)
      } else {
        (pay)
      }
    },
    bindWx() {
      ({
        success: function (res: any) {
          let data = ''
          if (res) {
            let appid = ''
            if () {
              appid = 
            }
            data = ([appid, ])
          }
          ('bindWx', data, false)
        },
        fail: function (err: any) {
          ('bindWx fail', err)
          ('bindWx', '', false)
        },
      })
    },
    openLocation(adress: string) {
      const data = (adress)
      ({
        latitude: Number(),
        longitude: Number(),
        name: ,
        scale: 18,
        complete: e => {
          ('openLocation complete', e)
        },
      })
      ('openLocation data', data)
    },
    downloadAndSave(res: string) {
      const data = (res)
      const $delay = data['$delay']
      if ($delay > 0) {
        setTimeout(() => {
          ({
            url: ,
            success: function (res) {
              ({
                filePath: ,
                fileType: 'pdf',
                showMenu: true,
              })
            },
          })
        }, $delay)
      } else {
        ({
          url: ,
          success: function (res) {
            ({
              filePath: ,
              fileType: 'pdf',
              showMenu: true,
            })
          },
        })
      }
    },
    callFun(res: string) {
      const data = (res)
      // @ts-ignore
      const fun = wx[data['$fun']]
      if (fun) {
        delete data['$fun']
        const $delay = data['$delay']
        if ($delay > 0) {
          delete data['$delay']
          setTimeout(() => {
            (wx, data)
          }, $delay)
        } else {
          (wx, data)
        }
      }
    },
  },
  mpRecieverMsg(key: string, val?: string) {
    // @ts-ignore
    const fun = [key]
    if (fun) {
      fun(val)
      return
    }
  },
}

(3)

// private property
let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

// private method for UTF-8 encoding
let _utf8_encode = function (str: string) {
  str = (/\r\n/g, "\n");
  let utftext = "";
  for (let n = 0; n < ; n++) {
    let c = (n);
    if (c < 128) {
      utftext += (c);
    } else if ((c > 127) && (c < 2048)) {
      utftext += ((c >> 6) | 192);
      utftext += ((c & 63) | 128);
    } else {
      utftext += ((c >> 12) | 224);
      utftext += (((c >> 6) & 63) | 128);
      utftext += ((c & 63) | 128);
    }
  }
  return utftext;
}

// private method for UTF-8 decoding
let _utf8_decode = function (utftext: string) {
  let string = "";
  let i = 0;
  let c, c1, c2, c3
  c = c1 = c2 = 0;
  while (i < ) {
    c = (i);
    if (c < 128) {
      string += (c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c2 = (i + 1);
      string += (((c & 31) << 6) | (c2 & 63));
      i += 2;
    } else {
      c2 = (i + 1);
      c3 = (i + 2);
      string += (((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
      i += 3;
    }
  }
  return string;
}

const Base64 = {
  // public method for encoding
  encode(input: string) {
    let output = "";
    let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    let i = 0;
    input = _utf8_encode(input);
    while (i < ) {
      chr1 = (i++);
      chr2 = (i++);
      chr3 = (i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
  },

  // public method for decoding
  decode(input: string) {
    let output = "";
    let chr1, chr2, chr3;
    let enc1, enc2, enc3, enc4;
    let i = 0;
    input = (/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < ) {
      enc1 = _keyStr.indexOf((i++));
      enc2 = _keyStr.indexOf((i++));
      enc3 = _keyStr.indexOf((i++));
      enc4 = _keyStr.indexOf((i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + (chr1);
      if (enc3 != 64) {
        output = output + (chr2);
      }
      if (enc4 != 64) {
        output = output + (chr3);
      }
    }
    output = _utf8_decode(output);
    return output;
  },

  // Encoding  encode64(str: string, uri: boolean = true) {
    str = (str);
    if (uri) {
      str = (/[+|=|/]/g, function (word) {
        switch (word) {
          case "+":
            return "-";
          case "=":
            return "_";
          case "/":
            return ".";
        }
        return word;
      });
    }

    return str;
  },

  // Decode  decode64(str: string, uri: boolean = true) {
    if (uri) {
      str = (/[-|_|.]/g, function (word) {
        switch (word) {
          case "-":
            return "+";
          case "_":
            return "=";
          case ".":
            return "/";
        }
        return word;
      });
    }
    str = (str);
    return str;
  },
}

export default Base64

<template>
  <web-view :src="src" @message="receiveMessage"> </web-view>
</template>

<script lang="ts">
import { cfg } from '@/cfg'
import { App } from '@/store/app'
import Base64 from '@/utils/Base64'
export default {
  data() {
    return {
      src: '',
      srcP: '',
      shareData: {
        imageUrl:
          '//static/images/20240122/' +
           +
          '.png?x-oss-process=image/auto-orient,1/resize,m_fixed,w_100,h_100',
      },
      shareI: '',
    }
  },
  onLoad(e: any) {
    // The generated applet code must be this key    (,  || )

    ({
      withShareTicket: true,
      menus: ['shareAppMessage'],
      success(res) {
        ('mixin share success', res ? (res) : res)
      },
      fail(err) {
        ('mixin share fail', err ? (err) : err)
      },
    })
  },
  onShow() {
     = 
     = {}
  },
  onShareAppMessage(res: any) {
    (res)
    if ( === 'button') {
      return 
    }
    if ( === 'menu') {
      return  || {}
    }
  },

  onShareTimeline() {
    let data = {
      title: 'Yiyi Art Villa',
      query: 'id=1',
      // imageUrl: '',
    }
    return data
    // return  || {};
  },
 

  onHide() {},
  methods: {
    setSrc(src: string, shareI?: string) {
      let cert = ( + 'userStorageCert')
      ('setSrc src', src)
      ('setSrc shareI', shareI)
      let i = ('#')
      let j = ('?')
      let srcP = i > 0 && i < j ? (0, i) : j > 0 ? (0, j) : src
      if (srcP && srcP[ - 1] != '/') {
        srcP = srcP + '/'
      }

      if (i > 0) {
         = (0, i)
      } else {
         = 
      }
      ('[   ] >', )

       = srcP
       = 
      src = j > 0 ? src + '&_mpid_=' +  : src + '?_mpid_=' + 
      if (shareI) {
        src = src + '&_i=' + shareI
        // Share address splicing        const startIndex = ('#')
        const endIndex = ('?')
        if (startIndex !== -1 && endIndex !== -1) {
          src = (0, startIndex) + (endIndex)
          (src)
        }
         = shareI
      }
      src = src + '&ver=' + 

      if (cert) {
        src = src + '&_cert_=' + encodeURIComponent(cert)
      }
       = src
      ('setSrc ', )
    },
    // Listen to h5 messages    // { merge user information imageUrl default sharing image path sharing address title: share title desc }    receiveMessage(e: any) {
      ('receiveMessage333', e)
      let arr = e?.detail?.data
      let data = arr &&  > 0 ? arr[ - 1] : null
      let url
      if (data && data?.merber?.id) {
        url = data?.path
          ? 
          :  == 'mp_wdysj'
          ? 'pages/artisthome/artisthome'
          : '/pagesShop/shop/wHome'
        let parms = (url, false, { mmId: data?. }, 13050, data?.merber?.id)
        ('data222', data)
         = {
          path: '/pages/index/index?i=' + parms + '&fk=1',
          imageUrl: data?.imageUrl
            ? 
            : '//static/images/20240122/' +
               +
              '.png?x-oss-process=image/auto-orient,1/resize,m_fixed,w_100,h_100',
          title: data?.title ?  : ,
          desc: data?.desc ?  : '',
          query: parms,
        }
      } else {
        ()
      }
    },
    // Address encryption    gen(uri: string, bind: boolean, reg: any, eid?: number, memberId?: number): string {
      // Standard code      let ps = [memberId, '', false, uri || '', reg || '', eid]
      for (let i =  - 1; i >= 0; i--) {
        if (ps[i]) {
          let del =  - i - 1
          if (del > 0) {
            (i + 1, del)
          }

          break
        }
      }
      let _ps: any = ps
      _ps[0] = _ps[0] || ''
      if (bind) {
        _ps[2] = uri
        _ps[3] = ''
      } else {
        _ps[2] = ''
      }

      return Base64.encode64((ps))
    },
  },
}
</script>

<style></style>

export const cfg = {
  mpApp: 'mp_wdysj', //Yiyi Art Mall  mpName: 'Yiyi Art Mall',
  mpUrl: '/xxx/',
  mpid: '',
  mpSrcP: '',
  version: '1.0.8',
  entryUrl: '/xxx/#/pagesShop/shop/wHome',
}

const info = ()
if (!) {
  const host = 
  // @ts-ignore
  if (host && ) {
    // @ts-ignore
     = 
  }

  if (!) {
     = 
  }
}
export default cfg

2. h5 end

(1) When the project is initialized, h5 is loaded into WeChat sdk

 // #ifdef H5
  let _mpid_;

  try {
    let search = <any>(
      (launcher.h5Search || ab_.route(false, false, false).search)
    );

    _mpid_ = search['_mpid_'];
    let _cert_ = search['_cert_'];

    // Get the certificate passed by the applet    if (_cert_) {
      _cert_ = decodeURIComponent(_cert_)
       = _cert_
    }
    let app =  || 'web'
    if (()) {
      ().wait("weixinLogin");
      ab_.reqJs(
        
          ? "/open/js/jweixin-1.6."
          : "/open/js/jweixin-1.6.",
        null,
        function () {
          function wxH5() {
            if (search["code"]) {
              let parms: Array<string> = [, search["code"]];
              (
                "wx",
                function (logined) {
                  ("WeChat login successfully", logined);
                  try {
                    if (logined) {
                      ("wxLogined", {
                        token: ["atoken"],
                        authPar: ,
                        authParas: ,
                      });
                    } else {
                      ("wxLogined", {});
                    }
                  } finally {
                    ().done("weixinLogin");
                    // WeChat jsConfig                    ();
                  }
                },
                parms,
                true,
                true,
                true
              );
            } else {
              try {
                // Turn off automatic login                //  = false;
                let wxLogined = ("wxLogined");
                if (wxLogined &&  &&  && [0] === app) {
                  (, (logined) => {
                    if (logined) {
                       = ;
                       = ;
                      ().done("weixinLogin");
                    } else {
                      //WeChat browser to lift WeChat payment, you must obtain openid                      ("We must obtain openid when you drop WeChat payment");
                      Weixin.snsapi_base();
                    }
                  });
                } else {
                  //WeChat browser to lift WeChat payment, you must obtain openid                  ("We must obtain openid when you drop WeChat payment");
                  Weixin.snsapi_base();
                }
              } finally {
                // WeChat jsConfig                ();
              }
            }
          }
          // @ts-ignore
          if () {
             = false;
            try {
              // @ts-ignore
              if (typeof WeixinJSBridge == "object" && typeof  == "function") {
                handleFontSize();
              } else {
                if () {
                  ("WeixinJSBridgeReady", handleFontSize, false);
                  // @ts-ignore
                } else if () {
                  // @ts-ignore
                  ("WeixinJSBridgeReady", handleFontSize);
                  // @ts-ignore
                  ("onWeixinJSBridgeReady", handleFontSize);
                }
              }
              function handleFontSize() {
                // Set the web font to the default size                // @ts-ignore
                ('setFontSizeCallback', { 'fontSize': 0 });
                // Rewrite the event that sets the web font size                // @ts-ignore
                ('menu:setfont', function () {
                  // @ts-ignore
                  ('setFontSizeCallback', { 'fontSize': 0 });
                });
              }

              // @ts-ignore
              if () {
                // @ts-ignore
                ((res) => {
                  if () {
                     = true
                     = true;
                    // && search['_mpid_'] == "mp_wdysj_shop"
                    if (_mpid_) {
                      if ((_mpid_ == "mp_wdysj_shop" || _mpid_ == "mp_wdysj_yiyi_shop")) {
                         = "Mall"
                         = "/pagesShop/shop/wHome"
                         = 'Mall'
                        ('platform', 'mp')
                         = _mpid_
                         = 13061
                      }
                       = _mpid_
                       = _mpid_
                    }
                    // Mini Program                    Weixin.initWxMpH5(_mpid_, search['ver'])
                    ().done("weixinLogin");
                  } else {
                    wxH5()
                  }
                })

                return
              }

            } catch (e) {
              (e)
            }

            wxH5()

          } else {
            ().done("weixinLogin");
          }
        },
        undefined
      );

    } else {
    }

  } catch (e) {
    (e);
  }
  // #endif

3、

import ab_ from 'axj-ab_'; //npm install axj-ab_
import Base64 from '../util/Base64';

interface ShareInfo {
  title: string,
  desc?: string,
  link: string,
  imageUrl?: string,
  logo?: string,//Compatible with old projects  imgUrl?: string,//Compatible with old projects  scene?: string
}

let weixin = false;
let readyReg = false;
let wxConfigState = -1;
let wxMpH5 = false;
let wxMpApp = '';
// let wxMpToken = '';

const Weixin = {
  initStepsArray: [1000, 2000, 4000, 8000, 16000, 32000, 64000],
  initI: 0,
  erred: false,
  readyed: false,
  shareInfo: <undefined | ShareInfo>undefined,
  // If wx authorization fails, the authorization will be obtained again regularly  wxConfigRe(e?: any) {
    ('wxConfig error ' + e)
    // alert('wxConfig error ' + (e))
     = true
    // @ts-ignore
    setTimeout(,  <  ? [++] : [ - 1])
  },
  // Verify configuration through the config interface  wxConfig() {
    let authUrl = 
    wxConfigState++
    switch (wxConfigState) {
      case 1:
        authUrl = Ainit.h5Href
        break
      // case 2:
      //   authUrl =  + '//' +  +  +  + 
      //   break
      default:
        wxConfigState = 0
        break
    }
	//You can write the method of debugging interface authorization yourself    (-1, 'C/wxConfig', [, authUrl], function (err, rep) {
      ('pltClient C/wxConfig err,data:', err, rep)
      if (rep && ) {
        //  = true
         = [
          'updateAppMessageShareData',
          'updateTimelineShareData',
          'onMenuShareAppMessage',
          'onMenuShareTimeline',
          "getLocation",
          "scanQRCode",
          // 'wx-open-launch-weapp',
          // 'chooseWXPay'
        ]
        //  = true
        ('wxready  ')
         = false
        // @ts-ignore
        (rep)
        // @ts-ignore
        ()
        let readyFun = function () {
          if () {
            return
          }
           = true
        }

        if (readyReg) {
          setTimeout(readyFun, 1000);

        } else {
          readyReg = true
          // @ts-ignore
          (readyFun)
        }

        return;
      }

      ()
    })

  },
  wxShare(v: ShareInfo) {
    ('h5  wxShare alert', v);
    if (weixin) {
      // @ts-ignore
      v = typeof (v) === 'object' ? v : (v)
      if (!) {
         = v
        return
      }

      delete 
      var share = {
        title:  || 'xx', // Share the title        desc:  || '', // Share the description        link: , // Share the link. The domain name or path of the link must be consistent with the official account JS security domain name corresponding to the current page.        imgUrl:  ||  || , // Share icon        success: (e) => {
          ('wxShare success  ', e)
          // Show WeChat Share          // @ts-ignore
          // if () {
          //   // @ts-ignore
          //   ('showOptionMenu')
          // }
          if ( && ) {
            // @ts-ignore
            ({
              menuList: [
                'menuItem:share:appMessage',
                'menuItem:share:timeline',
                'menuItem:favorite',
                'menuItem:share:qq',
                'menuItem:share:QZone',
              ]
            })
          }
        },
        fail: function (e) {
          ('wxShare fail', e)
        }
      }
      ('updateWx', share)
      // @ts-ignore
      (share)
      // @ts-ignore
      (share)

      // ("showOptionMenu");
    }
  },
  // Silent authorization  snsapi_base() {
    var backUri = Ainit.h5Href || 
    (backUri)
    var redirectUri = axConfig.pltH5 + 'static/?u=' + Base64.encode64(backUri, true)
    redirectUri =
      '/connect/oauth2/authorize?appid=' + ( == 'wdysjh5' ? 'wxab385cf8a7ec96d8' : 'wx59a0fb7a9bd076e5') + '&redirect_uri=' +
      encodeURIComponent(redirectUri) +
      '&response_type=code&scope=snsapi_userinfo&state=1'
    (redirectUri)
    (redirectUri)
    // setTimeout(() => {
    //   (redirectUri)
    // }, 3000);
  },
  isWeiXin() {
    return weixin;
  },
  isWxMpH5() {
    return wxMpH5
  },
  getWxMpApp() {
    return wxMpApp
  },
  initWxMpH5(mpid: string, ver?: string) {
    ('initWxMpH5 ' + mpid)
    weixin = false
    wxMpH5 = true

    if (mpid) {
      wxMpApp = mpid

    } else {
      ('initWxMpH5 no mpid' + )
      (launcher.h5Href)
      (launcher.h5Search)
    }

    (`mp-${ver}`)
    // Message channel    setInterval(function () {
      let msg = ('_mpmsg_')
      if (msg) {
        try {
          msg = (msg)
          if (!mpid || msg[0] === mpid) {
            // It's a message sent to me            msg = msg[1]
            msg = Base64.decode64(msg)
            let i = (',')
            if (i > 0) {
              ((0, i), (i + 1))

            } else {
              (msg, '')
            }

            ('_mpmsg_')
          }

        } catch (e) {
          (e)
          ('_mpmsg_')
        }
      }

    }, 100)
  },
  onWxMpMsg(key: string, val?: string) {
    ('onWxMpMsg,' + key + ',' + val)
    if (key == 'pay') {
      ('updatePay, update payment status' + key)
      uni.$emit('updatePay', { msg: 'Update payment status' })
    }
    // @ts-ignore
    ()
    let fun = [key]
    if (fun) {
      fun(val)
    }
  },
  forWxMpToken(back: (err?: any) => void) {
    if () {
      back && back()
      return
    }

    // @ts-ignore
    let nextT = ab_.nextT()
    // @ts-ignore
    Weixin['forWxMpTokenBacks'] = [nextT, back]
    // @ts-ignore
    ({ url: '/pages/msg/post?loginA=' + nextT })
  },
  onWxMpCenter: {
    loginA(val: string) {
      let paras = (val)
      let nextT = 0
      let back: any
      let loginA = false
      if (typeof (paras[0]) === 'number') {
        loginA = true
        nextT = paras[0]
        paras = ab_.args(paras, 1, )
        let backs = Weixin['forWxMpTokenBacks']
        if (backs) {
          delete Weixin['forWxMpTokenBacks']
          if (backs[0] === nextT) {
            back = backs[1]
          }
        }
      }

      let noRep = nextT && 
      ('wx', (succ, rep) => {
        ('loginA ', succ, rep)
        if (succ) {
          ()
          if (loginA) {
            // @ts-ignore
            ()
          }

        } else if (! && !nextT) {
          ('toLogin--------')
          ('toLogin')
        }

        // Callback        back && back( ? undefined : rep)

      }, paras, false, 2, false, noRep)
    },
    loginAFail(val: string) {
      let paras = (val)
      let nextT = paras[0]
      let backs = Weixin['forWxMpTokenBacks']
      if (backs) {
        delete Weixin['forWxMpTokenBacks']
        if (backs[0] === nextT) {
          backs[1] && backs[1](paras[1])
        }
      }
    },
    loginInfo(val: string) {
      //let loginInfo = (val)
      let paras = (val)
      if () {
        paras[1] = 
      }

      ('wx', (succ) => {
        if (succ) {
          ()

        } else if (!) {
           = ''
        }

      }, paras, true, 2)
    },
    bindWx(val: string) {
      uni.$emit('updateBindWx', { msg: val })
    }
  },
  postWxMpMsg(key: string, val?: string) {
    ('postWxMpMsg,' + key + ',' + val)
    if (key === 'toLogin') {
      // ios new WeChat user logged in for the first time will cause this logic to not be executed      setTimeout(() => {
        // @ts-ignore
        ({ url: '/pages/index/login?t=' +  })
      }, 400);
      return
    }

    // if (key === 'toLoginA') {
    //   // @ts-ignore
    //   ({ url: '/pages/index/login' })
    //   return
    // }

    if (key === 'share') {
      // @ts-ignore
      ({ url: '/pages/msg/share?s=' + val })
      return
    }

    let msg = val ? (key + ',' + val) : key
    setTimeout(() => {
      // @ts-ignore
      ({ url: '/pages/msg/reciver?msg=' + Base64.encode64(msg) })
    }, 400);
    ('');
  },
}

// #ifdef H5
try {
  // WeChat environment judgment  let userAgent: any = ();
  weixin =
    (/MicroMessenger/i) == "micromessenger" &&
    !( &&  !== window);

  //Compatible WeChat payment path  if (weixin) {
    let h5Uri = ;
    if (('/#/') < 0) {
      // ().wait("weixinHref");
      try {
        h5Uri =  +  + "#/" + 
         = h5Uri
        setTimeout(() => {
          ()
        }, 1000);
        ().wait("weixinHref");
      } catch (error) {

      }
    }
  }

} catch (e) {
  (e);
}
// #endif

export default Weixin;

4. Public h5 jump page

<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1.0,maximum-scale=1,viewport-fit=cover"
    />
    <title>···</title>

    <style>
      #loadingBg {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 10000;
        top: 0;
      }
      body {
        margin: 0px;
        font-size: 12px;
      }
      #preloader {
        position: absolute;
        width: 30px;
        height: 30px;
        background: rgba(253, 87, 17, 1);
        border-radius: 50px;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        -webkit-animation: preloader_1 1.5s infinite linear;
        -moz-animation: preloader_1 1.5s infinite linear;
        -ms-animation: preloader_1 1.5s infinite linear;
        animation: preloader_1 1.5s infinite linear;
      }
      #preloader:after {
        position: absolute;
        width: 50px;
        height: 50px;
        border-top: 10px solid rgba(255, 139, 9, 1);
        border-bottom: 10px solid rgba(255, 139, 9, 1);
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
        border-radius: 50px;
        content: "";
        top: -20px;
        left: -20px;
        -webkit-animation: preloader_1_after 1.5s infinite linear;
        -moz-animation: preloader_1_after 1.5s infinite linear;
        -ms-animation: preloader_1_after 1.5s infinite linear;
        animation: preloader_1_after 1.5s infinite linear;
      }

      @-webkit-keyframes preloader_1 {
        0% {
          -webkit-transform: rotate(0deg);
        }
        50% {
          -webkit-transform: rotate(180deg);
          background: #ff4f11;
        }
        100% {
          -webkit-transform: rotate(360deg);
        }
      }
      @-webkit-keyframes preloader_1_after {
        0% {
          border-top: 10px solid rgba(253, 87, 17, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
        50% {
          border-top: 10px solid rgba(253, 87, 17, 1);
          border-bottom: 10px solid rgba(253, 87, 17, 1);
        }
        100% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
      }

      @-moz-keyframes preloader_1 {
        0% {
          -moz-transform: rotate(0deg);
        }
        50% {
          -moz-transform: rotate(180deg);
          background: #ff4f11;
        }
        100% {
          -moz-transform: rotate(360deg);
        }
      }
      @-moz-keyframes preloader_1_after {
        0% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
        50% {
          border-top: 10px solid rgba(253, 87, 17, 1);
          border-bottom: 10px solid rgba(253, 87, 17, 1);
        }
        100% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
      }

      @-ms-keyframes preloader_1 {
        0% {
          -ms-transform: rotate(0deg);
        }
        50% {
          -ms-transform: rotate(180deg);
          background: #ff4f11;
        }
        100% {
          -ms-transform: rotate(360deg);
        }
      }
      @-ms-keyframes preloader_1_after {
        0% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
        50% {
          border-top: 10px solid rgba(253, 87, 17, 1);
          border-bottom: 10px solid rgba(253, 87, 17, 1);
        }
        100% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
      }

      @keyframes preloader_1 {
        0% {
          transform: rotate(0deg);
        }
        50% {
          transform: rotate(180deg);
          background: #ff4f11;
        }
        100% {
          transform: rotate(360deg);
        }
      }
      @keyframes preloader_1_after {
        0% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
        50% {
          border-top: 10px solid rgba(253, 87, 17, 1);
          border-bottom: 10px solid rgba(253, 87, 17, 1);
        }
        100% {
          border-top: 10px solid rgba(255, 139, 9, 1);
          border-bottom: 10px solid rgba(255, 139, 9, 1);
        }
      }
    </style>
  </head>
  <script>
    function getPara(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = (1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    }

    let uid = getPara("uid");
    let msg = getPara("msg");
    if (msg) {
      ("_mpmsg_", ([uid, msg]));
    }
  </script>
  <body>
    <div >
      <div ></div>
      <!-- <div>loading</div> -->
    </div>
  </body>
</html>

Summarize

This is the article about uniapp WeChat mini program webview and h5 data communication. For more related uniapp mini program webview and h5 data communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!