Table of Contents
Functions provided by mini programs
A simple way to get communication
Summary
A little poem
Home WeChat Applet Mini Program Development A brief analysis of how to communicate between web pages and small programs

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

Dec 07, 2021 am 09:51 AM
Applets Web page communication

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) });
Copy after login

小program

index. wxml

Receive events through bindmessage binding

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

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,
  };
}
Copy after login

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(() => {});
};
Copy after login

小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);
    }
  },
});
Copy after login

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.

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

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

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

【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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send web pages to desktop as shortcut in Edge browser? How to send web pages to desktop as shortcut in Edge browser? Mar 14, 2024 pm 05:22 PM

How to send web pages to the desktop as a shortcut in Edge browser? Many of our users want to display frequently used web pages on the desktop as shortcuts for the convenience of directly opening access pages, but they don’t know how to do it. In response to this problem, the editor of this issue will share the solution with the majority of users. , let’s take a look at the content shared in today’s software tutorial. The shortcut method of sending web pages to the desktop in Edge browser: 1. Open the software and click the "..." button on the page. 2. Select "Install this site as an application" in "Application" from the drop-down menu option. 3. Finally, click it in the pop-up window

New generation of optical fiber broadband technology - 50G PON New generation of optical fiber broadband technology - 50G PON Apr 20, 2024 pm 09:22 PM

In the previous article (link), Xiao Zaojun introduced the development history of broadband technology from ISDN, xDSL to 10GPON. Today, let’s talk about the upcoming new generation of optical fiber broadband technology-50GPON. █F5G and F5G-A Before introducing 50GPON, let’s talk about F5G and F5G-A. In February 2020, ETSI (European Telecommunications Standards Institute) promoted a fixed communication network technology system based on 10GPON+FTTR, Wi-Fi6, 200G optical transmission/aggregation, OXC and other technologies, and named it F5G. That is, the fifth generation fixed network communication technology (The5thgenerationFixednetworks). F5G is a fixed network

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

Possible reasons why the network connection is normal but the browser cannot access the web page Possible reasons why the network connection is normal but the browser cannot access the web page Feb 19, 2024 pm 03:45 PM

The browser cannot open the web page but the network is normal. There are many possible reasons. When this problem occurs, we need to investigate step by step to determine the specific cause and solve the problem. First, determine whether the webpage cannot be opened is limited to a specific browser or whether all browsers cannot open the webpage. If only one browser cannot open the web page, you can try to use other browsers, such as Google Chrome, Firefox, etc., for testing. If other browsers are able to open the page correctly, the problem is most likely with that specific browser, possibly

What to do if the webpage cannot be opened What to do if the webpage cannot be opened Feb 21, 2024 am 10:24 AM

How to solve the problem of web pages not opening With the rapid development of the Internet, people increasingly rely on the Internet to obtain information, communicate and entertain. However, sometimes we encounter the problem that the web page cannot be opened, which brings us a lot of trouble. This article will introduce you to some common methods to help solve the problem of web pages not opening. First, we need to determine why the web page cannot be opened. Possible reasons include network problems, server problems, browser settings problems, etc. Here are some solutions: Check network connection: First, we need

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

How to open php on the web page How to open php on the web page Mar 22, 2024 pm 03:20 PM

Executing PHP code in a web page requires ensuring that the web server supports PHP and is properly configured. PHP can be opened in three ways: * **Server environment:** Place the PHP file in the server root directory and access it through the browser. * **Integrated Development Environment: **Place PHP files in the specified web root directory and access them through the browser. * **Remote Server:** Access PHP files hosted on a remote server via the URL address provided by the server.

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

See all articles