You can create a webviewContext to send messages from a Mini Program to a web-view component.
This feature is supported in base libraries 1.8.0 and later. For earlier versions, you must handle compatibility. For more information, see Mini Program base libraries.
This feature is supported in mPaaS 10.1.32 and later.
my.createWebViewContext(webviewId)
This API creates and returns a webViewContext object to send messages from a Mini Program to a web-view component.
Parameters
Parameter | Type | Required | Description |
webviewId | String | Yes | The ID of the |
Return value
A webViewContext object.
A webViewContext object is attached to a web-view component by the component's webviewId. You can use the webViewContext object to implement features.
The methods of the webViewContext object are as follows:
Method | Parameter | Description | Compatibility |
postMessage | Object | Sends a message from the Mini Program to the |
Code examples
<view>
<web-view id="web-view-1" src="..." onMessage="onMessage"></web-view>
</view>Page({
onLoad() {
this.webViewContext = my.createWebViewContext('web-view-1');
},
// Receive messages from the H5 page
onMessage(e) {
console.log(e); //{'sendToMiniProgram': '0'}
// Send a message to the H5 page
this.webViewContext.postMessage({'sendToWebView': '1'});
}
})// In the JavaScript code of the H5 page, define my.onMessage to receive messages from the Mini Program.
my.onMessage = function(e) {
console.log(e); //{'sendToWebView': '1'}
}
// The H5 page sends a message to the Mini Program.
my.postMessage({'sendToMiniProgram': '0'});In the bidirectional communication flow shown, the H5 page first sends a message to the Mini Program. After receiving the message, the Mini Program sends a message back to the H5 page.