Author: Guomye


Reference:
BBS. Quickapp. Cn/forum. PHP? M…

background

Quick application version: 1020

When using Web components to communicate between fast applications and web pages, there are several findings:

1. Running ‘NPM run watch’ prompts web components not to support message events, which they do (just a glitch in the prompts)

2, fast application to send information to the web page, and the web to send information to fast application, using the method name is postMessage, but the data format is not consistent, it is not convenient to use

3. Messages will be lost (such as sending messages to web pages before the message processing function has been executed)

4. When a web page sends a message to a fast application, the message sent by the fast application to the web page will be returned

The characteristics of

Therefore, here is an auxiliary library made with some effort, features:

1. Messages are sent in an orderly manner

2, the message will not be lost, guaranteed to arrive

3. Messages will not be received more than once (deduplicated)

4, message type, similar events monitoring mechanism, more convenient

Fast application side code

In the quick application, create a new channel.js file with the following contents:

<template>
    <web id="web" src="xxx" @message="{{onMessage}}"></web>
</template>

<script>
    import Channel from './channel'

    export default {
        channel: null,
        onInit() {
            this.channel = new Channel(this, 'web'// Channel listener this.channel.on()'type1'.function(data) {// Process received data}) // Send message this.channel.sendmsg ('type2', {// data})}, onMessage(param) {this.channel.onmsg (param)},} </script>Copy the code

Page side code

Webside JS (you can create a new JS or copy it into a script):

/** * (on the HTML side, you can actually only create one channel per page) ** channel, which is used for reliable communication with HTML ** 1. * * @param logger {Function} null * @param timeout {Number} Timeout duration. The system will retry after the timeout, in ms. The default value is 1000 */ var Channel =function (logger, timeout) {
    timeout = timeout || 1000

    if(! Logger) logger = () => {} var that = this // message id generator that. IdGenerator = 0 // message sending queue that. SendQueue = [// {// data: {}, / / resolve: Object, / /}]. / / * * * list that listeners = {/ /typeReceivedId = 0 /** * @param: [listener1, listener2],type{String} Message type * @param data {Object} Message content * @return {Promise}
     */
    that.sendMsg = function (type, data) {
        var resolve;
        var promise = new Promise(resolve_ => resolve = resolve_)
        that.sendQueue.push({
            data: {
                pType: 'msg',
                id: ++that.idGenerator,
                type: type,
                data: data,
            },
            resolve
        })
        returnPromise} /** * listen * @paramtypeMessage type * @param callback callback */ that.on =function (type, callback) {
        var typeListeners = that.listeners[type] || []
        that.listeners[type] = typeListeners
        type** * Call (set to onMessage handler) */ that.onmsg =function (message) {
        logger('[Received message]' + message)
        var {pType, id, type, data} = JSON.parse(message)

        if (pType === 'ack') {//ack
            if(id == that. IdGenerator) {var nowPackets = that.sendqueue.splice (0, 1); that.valid_(nowPackets.length === 1) nowPackets[0].resolve() } }else if (pType === 'msg') {// Normal messageifReceivedId + 1) {// Is the next package to receive, valid // Update the cache value that. ReceivedId ++ // Process vartypeListeners = that.listeners[type] || []
                logger('[Processing message] Type: ' + type + Number of processors: + typeListeners.length)
                for (var i = 0; i < typeListeners.length; i++) {
                    try {
                        typeListeners[i](data)
                    } catch (e) {
                        logger('[Handle exception]'+ json.stringify (e))}} // Response ack that.send_({pType:'ack',
                    id,
                })
            }
        } else{// No pType, ignoredreturn}} /** * send packets */ that.send_ =function (packet) {
        var str = JSON.stringify(packet)
        system.postMessage(str)
        logger('[Send message]'+ STR)} /** * next_ =function () {
        ifSendQueue [0].data)}} /** * Validates */ that.valid_ =function (bool, errMsg) {
        if(! bool) { throw new Error(errMsg ||'Valid Fail! '}} // timer: retry sending packets continuouslysetInterval(function() {that.next_()}, timeout) // Timer: ping //setInterval(function() {that.send_({})}, 200) // Connect system.onMessage = that.onmsg}Copy the code


How to use webpage (for reference):

Var channel = new channel () var channel = new channel ()'type1'.function(data) {// Process received data}) // Send message channel.sendmsg ('type2', {// data})Copy the code

After the most

The format of the message is messageString, but the format is not stated in the document. In the official demo, you can see the code annotated in the format is {message: ‘XXX ‘}.

2. The log of the web page is not displayed well


Related reading:

A front-end siege lion fast application development path

Quick app usage and FAQ

Fast Application Development Ramble – Deployment and debugging

Quick application development beginner’s guide


Write in the last

In last year’s developer contest essay, we through multiple community joint activities have a large collection of high quality articles, a guide into the pit, open source projects, developing a template, summarize the common problems, and other aspects, these content provides reference for many developers, thanks for your support and participation, our the campaign continues this year, Interested developers can click to read the original to see the details!

In last year’s developer contest essay, we through multiple community joint activities have a large collection of high quality articles, a guide into the pit, open source projects, developing a template, summarize the common problems, and other aspects, these content provides reference for many developers, thanks for your support and participation, our the campaign continues this year, Interested developers can go to the following for details. The BBS quickapp. Cn/forum. PHP? M…





Fast Application ecosystem platform — enabling developers to expand scenarios into the future