my.createWebViewContext

Version requirements: Basic library 1.8.0 or higher version. If the version is low, suggest Compatible treatment.

By creating webviewContext, it creates the capability to send messages from Mini Program to web-view. Create and return web-view context webViewContext object.

Sample Code

copy
    <!-- .axml -->
    <view>
      <web-view id="web-view-1" src="..." onMessage="onMessage"></web-view>
    </view>
copy
    // .js
    Page({
      onLoad() {
        this.webViewContext = my.createWebViewContext('web-view-1');
      },
      // Receive message from HTML5
      onMessage(e) {
        console.log(e); //{'sendToMiniProgram': '0'}
        // Send message to HTML5
      this.webViewContext.postMessage({'sendToWebView': '1'});
      }
    })
copy
    // .js
    // my.onMessage needs to be defined in HTML5 js code at first to receive the message from Mini Program.
    my.onMessage = function(e) {
      console.log(e); //{'sendToWebView': '1'}
    }
    // HTML5 sends message to Mini Program
    my.postMessage({'sendToMiniProgram': '0'});

Note: The workflow of the above two-way communication capability is that HTML5 sends message to Mini Program at first. After the Mini Program receives the message, it sends message to HTML5.

Parameters

Object type with the following attributes:

AttributesTypeMandatoryDescription
webviewIdStringYesID attribute corresponding to the web-view to be created.

Return Value

Create a webViewContext object

webViewContext is bound with a web-view component via webviewId to implement some functions. List of webViewContext object methods:

MethodParametersDescriptionCompatibility
postMessageObjectThe Mini Program sends message to the web-view component, and works with the my.postMessage provided by web-view.js to implement the two-way communication between Mini Program and web-view page.1.8.0