Implementation of Two-Way Communication Between Quick Apps and Web Pages
The quick app framework provides two-way communication between quick apps and web pages. Let's discuss what this is, what it means, and how to implement it.
Join the DZone community and get the full member experience.Join For Free
- Can an HTML5 web page use the device API of a quick app to obtain device information?
- Can an HTML5 quick app integrate ad capabilities?
There are a lot of similar questions along these lines, and I’ll give you a simple answer: yes, you can. Of course, an HTML5 web page cannot call standard APIs of quick apps, but quick apps can. Can the information obtained by quick apps be passed to web pages? The answer is also yes. The quick app framework provides two-way communication between quick apps and web pages. You can send a request from a web page to a quick app and, after receiving it, the quick app processes the request and returns data to the web page.
How To Use
Implementation on the Quick App Side
On the quick app side, you can send messages to or listen to messages from a web page.
postMessage(): Sends a message to a web page. The sample code is as follows:
- onmessage event: Listens to messages sent from a web page. The web component defines the message event. During implementation, the onmessage event needs to be added to the web component. The sample code is as follows (see the red part):
Sample code of an onMessage handler of a response event is as follows:
Implementation on the HTML5 Web Page Side
system.postMessage(): Sends a message to a quick app. The sample code is as follows:
system.onmessage(): Receives a message from a quick app. The sample code is as follows:
Note: The preceding code must be added to the script under the head tag in the HTML file of the web page.
Integrating HUAWEI Ads Kit Into an HTML5 Quick App
The process is the same as that in Accessing HUAWEI Ads Publisher Service. The only difference lies in the logic of the ad display. After you call native ads APIs for a native quick app, the native ad is directly displayed on the xx.ux page. But for an HTML quick app, the native ad needs to be displayed on web pages, which means that the result of API calls is passed to xx.ux through two-way communication.
Rewarded ads in a quick app are full-screen ads, which are automatically displayed and do not require manual implementation. This can save you much work when accessing rewarded ads for an HTML5 quick app.
The following is the sample code for an HTML5 quick app to integrate Ads Kit. You can learn the principle of two-way web communication by referring to the code.
References from this project are included in the links below.
Opinions expressed by DZone contributors are their own.