You can provide Mini program the ability to send messages to web-view by creating webviewContext.
Note:
- The basic library 1.8.0 and above versions support this interface. The lower versions need to complete compatibility process. For the operation, see Mini program basic library.
- mPaaS 1.10.32 and above versions support this interface.
my.createWebViewContext(webviewId)
This interface is used to create and return web-view context webViewContext object.
Input parameters
| Name | Type | Required | Description |
|---|---|---|---|
| webviewId | String | Yes | The ID attribute corresponding to the web-view to be created. |
Return value
The return value is a webViewContext object. webViewContext is bound with a web-view component via webviewId to implement some functions through.
The methods of webViewContext object are as follows:
| Method | Parameter | Description | Compatibility |
|---|---|---|---|
| postMessage | Object | The Mini Program sends message to web-view component. Whit the help of my.postMessage in web-view.js, the two-way communication between Mini Program and web-view web pages is possible. |
1.8.0 |
Code sample
<view><web-view id="web-view-1" src="..." onMessage="onMessage"></web-view></view>
Page({onLoad() {this.webViewContext = my.createWebViewContext('web-view-1');},// Receive the message from H5onMessage(e) {console.log(e); //{'sendToMiniProgram': '0'}// Send message to H5this.webViewContext.postMessage({'sendToWebView': '1'});}})
In the two-way communication procedure, H5 firstly sends message to Mini Program. After receiving the message, Mini Program sends message to H5.
// In the JS code of H5, my.onMessage need to be firstly defined to receive the messages from Mini program.my.onMessage = function(e) {console.log(e); //{'sendToWebView': '1'}}// H5 sends message to Mini programmy.postMessage({'sendToMiniProgram': '0'});