In WeChat Mini Programs, we can embed third-party web pages using the web-view component. If you need to exchange data between the Mini Program and the embedded page in web-view, you can send messages using the postMessage method. Here are the steps to achieve this functionality:
1. Add the web-view Component to the Mini Program
First, add a web-view component to the Mini Program's page and specify the URL of the web page to load.
xml<!-- Page's wxml file --> <web-view src="https://www.example.com" id="myWebview"></web-view>
2. Send Messages to web-view
You can use the postMessage method in the logic layer of the Mini Program (JavaScript file) to send messages to web-view. For example, you can send data when an event is triggered:
javascript// Page's js file Page({ sendMessage: function() { const webview = wx.createSelectorQuery().select('#myWebview'); webview.context(function(res) { res.context.postMessage({ data: 'Hello from MiniProgram' }); }).exec(); } });
In this example, you define a sendMessage method that first retrieves the context of the web-view component using createSelectorQuery and select, then sends an object containing data using postMessage.
3. Receive Messages in the web-view Page
The web page loaded in web-view needs to add appropriate event listeners to receive messages from the Mini Program. This is typically done by listening for the message event:
javascript// In the JavaScript file of the web page loaded in web-view window.addEventListener('message', function(event) { console.log('Received message from MiniProgram:', event.data); });
In this example, you add an event listener to the window object to handle the message event. When web-view receives a message from the Mini Program, it logs the message content.
Summary
By following these steps, you can achieve bidirectional data exchange between the WeChat Mini Program and the web page in web-view. This is very useful when integrating external web page functionality into the Mini Program. During development, ensure that the web page loaded in web-view allows Cross-Origin Resource Sharing (CORS); otherwise, you may encounter security or data access restrictions.