All Products
Search
Document Center

Mobile Platform as a Service:Webview component control

Last Updated:Feb 04, 2021

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

  1. <view>
  2. <web-view id="web-view-1" src="..." onMessage="onMessage"></web-view>
  3. </view>
  1. Page({
  2. onLoad() {
  3. this.webViewContext = my.createWebViewContext('web-view-1');
  4. },
  5. // Receive the message from H5
  6. onMessage(e) {
  7. console.log(e); //{'sendToMiniProgram': '0'}
  8. // Send message to H5
  9. this.webViewContext.postMessage({'sendToWebView': '1'});
  10. }
  11. })

In the two-way communication procedure, H5 firstly sends message to Mini Program. After receiving the message, Mini Program sends message to H5.

  1. // In the JS code of H5, my.onMessage need to be firstly defined to receive the messages from Mini program.
  2. my.onMessage = function(e) {
  3. console.log(e); //{'sendToWebView': '1'}
  4. }
  5. // H5 sends message to Mini program
  6. my.postMessage({'sendToMiniProgram': '0'});