“Live up to the time, the creation of non-stop, this article is participating in 2021 year-end summary essay competition”

One, foreword

Our wechat applet uses web-view to embed THE H5 project, so as to reduce the amount of development. In the actual use, we will meet the functional needs of web page and applet communication. Below, I simply summarize the problems I meet and the solutions.

Two, the function provided by the applets

WeChat provides web ways to send messages to the small program: wx. MiniProgram. PostMessage, sending a message to the small program, the method will be in a specific time (small back, component destroyed, sharing) message event trigger module.

You can check the wechat open documentation for details on the API

Take sharing as an example. If page A needs to set special sharing content, such as forwarding title and thumbnail, etc. You can set the variable value in the web page and send it to the applet

Web page

let shareData = {
  path: 'Forward path'.title: 'Custom Forwarding title'.imageUrl: 'Thumbnail URL'}; wx.miniProgram.postMessage({data: JSON.stringify(shareData) });
Copy the code

Small program

index.wxml

Receive events through the BindMessage binding

<web-view bindmessage='getMessage' src='{{ src }}'></web-view>
Copy the code

index.js

// Get the message sent from the web page
getMessage(e) {
  const getMessage (e) {
  // Data is an array of postMessage arguments
  const { data } = e.detail;
  // Need to fetch the last data
  let shareMessage = data[data.length - 1];
  this.shareMessage = JSON.parse(shareMessage);
};

// Set sharing
onShareAppMessage(options) {
  return {
    title: this.shareMessage.title,
    path:  this.shareMessage.path,
    imageUrl: this.shareMessage.imageUrl,
  };
}
Copy the code

This custom sharing is done once, but the postMessage method only gets messages for specific scenarios, so how do you get traffic for non-specific scenarios?

A simple method to obtain communication

The solution I provide may not be optimal or the most general, but it can be used as an alternative if problems occur.

3.1 Scenario Restoration

There is city positioning in our small program. When entering the small program for the first time, you need to select the city. After selecting the city, it will be cached locally. The functions are shown in the screenshot below.

Selecting a city will be displayed in the upper right corner of the home page

Because the city selection page and the home page are through the way of web-view embedded small program, so obviously in the H5 page into the cache, in the small program is unable to obtain the cache information.

3.2 Solutions

Solution is very simple, after I communicate with back-end companion, please give me his offer an interface, the city id and user information, so that I can to users with small program for user choose city id last time, and then again small program inside the cache handling, so that users enter the small program need not again again select cities

Web page

// Save the city information
const saveCityHandle = () = > {
  saveCity({
    cityId: cityId,
    userId: userId,
  }).then(() = > {});
};
Copy the code

Small program

The city ID is cached by wx.setStorageSync for future use.

wx.login({
  success(res) {
    if (res.code) {
      wx.request({
        url: `${that.domain()}/getUserInfo`.data: {
          body: { jsCode: res.code },
        },
        success(res) {
          wx.setStorageSync('cityId', res.data.cityId); }}); }else {
      console.log('Login failed! '+ res.errMsg); }}});Copy the code

Four,

“One can be a teacher by reviewing the old and learning the new.”

Sometimes look back to see some knowledge points, maybe there will be new ideas, with jun. ヾ (◍ ° ∇ ° ◍) ノ ゙

Five, a short poem

I looked at the date and found that December is the last month of 2021. I wrote a little poem before, which is somewhat in line with my current mood. I also have some wishes for myself and everyone.

Before my eyes is a window, outside the window is the changing scenery, night, dark green trees, scattered lights of high-rise buildings, speeding cars, or hurried or leisurely pedestrians. I seem to remember every building, but not every face, invariable buildings, changing passers-by. This year, there are some changes, every pursuit of life heart, are worth looking forward to, every reluctant eyes, smile can not cover up. To all the development partners, a pray, not with you, happiness and beauty.Copy the code