search
HomeWeChat AppletMini Program DevelopmentA brief analysis of how to communicate between web pages and small programs

How to communicate between web pages and mini programs? The following article will introduce you to the relevant knowledge about the communication between web pages and small programs. I hope it will be helpful to you!

A brief analysis of how to communicate between web pages and small programs

Our WeChat mini program uses the web-view method to embed H5 projects, thereby reducing the amount of development. In actual use, there will only be communication between the web page and the mini program. Function needs, below I briefly summarize the problems I encountered and the solutions.

Functions provided by mini programs

WeChat provides a method for web pages to send messages to mini programs: wx.miniProgram.postMessage. This method sends messages to mini programs. Trigger the message event of the component at a specific time (mini program retreat, component destruction, sharing).

Specific API details can be viewed WeChat Open Documentation

https://developers.weixin.qq.com/miniprogram/dev/component/web-view .html

Let’s briefly introduce how to use it, taking sharing as an example. If page A needs to set special sharing content, such as forwarding titles, thumbnails, etc. You can set the variable value in the web page and send it to the applet

webpage

let shareData = {
  path: '转发路径',
  title: '自定义转发标题',
  imageUrl: '缩略图url',
};
wx.miniProgram.postMessage({ data: JSON.stringify(shareData) });

小program

index. wxml

Receive events through bindmessage binding

<web-view bindmessage=&#39;getMessage&#39; src=&#39;{{ src }}&#39;></web-view>

index.js

// 获取从网页发送来的消息
getMessage(e) {
  const getMessage (e) {
  // data是多次postMessage的参数组成的数组
  const { data } = e.detail;
  // 需要取最后一条数据
  let shareMessage = data[data.length - 1];
  this.shareMessage = JSON.parse(shareMessage);
};

// 设置分享
onShareAppMessage(options) {
  return {
    title: this.shareMessage.title,
    path:  this.shareMessage.path,
    imageUrl: this.shareMessage.imageUrl,
  };
}

In this way, the customized sharing function is completed, but the postMessage method can only obtain messages in specific scenarios. So how to obtain communication if it is not a specific scenario?

A simple way to get communication

The solution I provide may not be the optimal or the most universal, but it can be used as a solution if you encounter a problem. An alternative.

1. Scene Restoration

Our mini program has city positioning. When entering the mini program for the first time, you need to select the city where you are located and select the city. It will be cached locally, and you no longer need to reselect the city when you enter the mini program again. The function is as follows screenshot

A brief analysis of how to communicate between web pages and small programs

After selecting the city, it will be displayed in the upper right corner of the homepage

A brief analysis of how to communicate between web pages and small programs

Since the city selection page and the homepage are both By embedding the mini program in the web-view, it is obvious that if the cache is entered in the H5 page, the cache information cannot be obtained in the mini program.

2. Solution

The solution is very simple. After communicating with my back-end partner, I asked him to provide me with an interface to The city id is associated with the user information, so that I can obtain the city id that the user last selected when the user entered the mini program, and then cache it in the mini program, so that the user does not need to select the city again when he enters the mini program again

Webpage

// 保存城市信息
const saveCityHandle = () => {
  saveCity({
    cityId: cityId,
    userId: userId,
  }).then(() => {});
};

小program

After obtaining the city id, cache it through wx.setStorageSync for subsequent use.

wx.login({
  success(res) {
    if (res.code) {
      wx.request({
        url: `${that.domain()}/getUserInfo`,
        data: {
          body: { jsCode: res.code },
        },
        success(res) {
          wx.setStorageSync(&#39;cityId&#39;, res.data.cityId);
        },
      });
    } else {
      console.log(&#39;登录失败!&#39; + res.errMsg);
    }
  },
});

Summary

"You can become a teacher by reviewing the past and learning the new."

Sometimes I look back at certain knowledge points. Maybe there will be new ideas to encourage you.ヾ(◍°∇°◍)ノ゙

A little poem

I glanced at the date and found that December is the last month of 2021. I used to I wrote a short poem, which is somewhat in line with my current state of mind. I also have some blessings for myself and everyone.

眼前是一扇窗,
窗外是变换的景色,
夜晚,
墨绿的树,
散落灯光的高楼大厦,
疾驰的汽车,
或匆忙或悠闲的行人。

我好像记住了每一座楼宇,
却不记得每一张面孔,
不变的建筑,
变换的路人。
今年,
有一些变化,
每一颗追求人生的心,
都值得期待,
每一个不舍的眼神,
笑容也无法遮掩。

致,
所有开发的伙伴,
一期一祈,
勿怀犹也,
幸福美好。

【Related learning recommendations: 小program development tutorial

The above is the detailed content of A brief analysis of how to communicate between web pages and small programs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.