Skip to main content

H5 and Mini Program Communication

This guide explains how to implement bidirectional message passing between H5 pages and WeChat Mini Programs, as well as how to detect the runtime environment.

Import WeChat JSSDK

The H5 page needs to import the WeChat JSSDK to communicate with the Mini Program:

<!-- H5 page needs to import WeChat JSSDK -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
Recommendation

It's recommended to use JSSDK version 1.6.0 or higher for better compatibility and feature support.

Sending Messages from H5 to Mini Program

Basic Usage

H5 pages can send messages to the Mini Program using wx.miniProgram.postMessage():

// H5 page JavaScript
// Send message to Mini Program
wx.miniProgram.postMessage({
data: {
action: 'getUserInfo',
payload: { userId: '12345' }
}
});

H5 pages can control Mini Program page navigation:

// Navigate back in Mini Program
wx.miniProgram.navigateBack({
delta: 1
});

// Navigate to other Mini Program pages
wx.miniProgram.navigateTo({
url: '/pages/profile/profile'
});

Environment Detection

Detect whether the current environment is a Mini Program:

// Check if running in Mini Program environment
wx.miniProgram.getEnv((res) => {
if (res.miniprogram) {
console.log('Currently in Mini Program environment');
} else {
console.log('Currently in regular browser environment');
}
});

Mini Program Receiving H5 Messages

Configure WebView

In the Mini Program page, you need to listen to the bindmessage event to receive messages from H5:

<!-- Mini Program page WXML -->
<web-view src="{{webviewUrl}}" bindmessage="handleMessage"></web-view>

Handle Messages

Handle received messages in the Mini Program page JavaScript:

// Mini Program page JS
Page({
data: {
webviewUrl: 'https://h5.example.com'
},

// Receive messages from H5
handleMessage(e) {
console.log('Received H5 message:', e.detail.data);

// e.detail.data is an array containing all data sent via postMessage
const messages = e.detail.data;

messages.forEach(msg => {
if (msg.action === 'getUserInfo') {
console.log('User ID:', msg.payload.userId);
// Handle business logic
}
});
}
});
Important Note

The bindmessage event is only triggered at specific times:

  • When navigating back in the Mini Program
  • When sharing
  • When the component is destroyed

Not triggered in real-time. If you need real-time communication, consider using WebSocket.

Complete Communication Example

Complete H5 Page Example

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H5 Page</title>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>
<h1>H5 Page</h1>
<button id="sendBtn">Send Message to Mini Program</button>
<button id="backBtn">Return to Mini Program</button>

<script>
// Get parameters passed by Mini Program
const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('userId');

// Send message button
document.getElementById('sendBtn').addEventListener('click', () => {
wx.miniProgram.postMessage({
data: {
action: 'fromH5',
message: 'Hello from H5',
userId: userId
}
});
alert('Message sent (will be triggered on return)');
});

// Back button
document.getElementById('backBtn').addEventListener('click', () => {
wx.miniProgram.navigateBack();
});

// Environment detection
wx.miniProgram.getEnv((res) => {
if (!res.miniprogram) {
alert('Please open in WeChat Mini Program');
}
});
</script>
</body>
</html>

Complete Mini Program Page Example

WXML:

<!-- pages/webview/webview.wxml -->
<web-view src="{{webviewUrl}}" bindmessage="handleMessage"></web-view>

JavaScript:

// pages/webview/webview.js
Page({
data: {
webviewUrl: ''
},

onLoad(options) {
// Pass data to H5 via URL parameters
const userId = options.userId || '';
this.setData({
webviewUrl: `https://h5.example.com?userId=${userId}`
});
},

// Receive H5 messages
handleMessage(e) {
console.log('Received H5 message:', e.detail.data);

const messages = e.detail.data;
messages.forEach(msg => {
switch(msg.action) {
case 'fromH5':
// Handle messages from H5
wx.showToast({
title: msg.message,
icon: 'none'
});
break;

case 'getUserInfo':
// Handle user info retrieval request
this.handleGetUserInfo(msg.payload);
break;

default:
console.warn('Unknown message type:', msg.action);
}
});
},

handleGetUserInfo(payload) {
// Implement user info retrieval logic
console.log('Get user info:', payload);
}
});

JSON Configuration:

{
"navigationBarTitleText": "H5 Page",
"enablePullDownRefresh": false
}

Advanced Tips

Passing Parameters to H5

Mini Programs can pass data to H5 via URL parameters:

// Mini Program passes parameters
Page({
data: {
webviewUrl: 'https://h5.example.com?token=xxx&scene=chat'
}
});
// H5 receives parameters
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
const scene = urlParams.get('scene');

Message Queue Handling

Since postMessage is not triggered in real-time, you can accumulate messages in H5:

// H5 message queue
const messageQueue = [];

function sendToMiniProgram(data) {
messageQueue.push(data);
wx.miniProgram.postMessage({ data });
}

// Send all messages when page is about to unload
window.addEventListener('beforeunload', () => {
if (messageQueue.length > 0) {
wx.miniProgram.postMessage({
data: {
action: 'batchMessages',
messages: messageQueue
}
});
}
});

Enhanced Environment Detection

A more robust environment detection solution:

// H5 environment detection
function checkMiniProgramEnv() {
return new Promise((resolve) => {
if (typeof wx === 'undefined' || !wx.miniProgram) {
resolve(false);
return;
}

wx.miniProgram.getEnv((res) => {
resolve(res.miniprogram === true);
});
});
}

// Usage example
checkMiniProgramEnv().then((isMiniProgram) => {
if (isMiniProgram) {
console.log('In Mini Program environment');
// Enable Mini Program-specific features
} else {
console.log('In regular browser');
// Fallback handling
}
});

FAQ

Messages Not Received?

  1. Check trigger timing: bindmessage is only triggered when navigating back, sharing, or destroying
  2. Check data format: Ensure postMessage data format is correct
  3. Check console: View logs in Mini Program developer tools

How to Implement Real-time Communication?

postMessage doesn't support real-time communication. For real-time needs, consider:

  • Using WebSocket
  • Using polling
  • Combining with Mini Program network API

Can H5 Receive Messages from Mini Program?

H5 cannot directly receive proactive messages from Mini Programs. Options include:

  • URL parameters for initial data
  • WebSocket bidirectional communication
  • Server-side relay