Two-Way Connection on Website
This page will introduce how the microservice webpage in the TownPass open-source project connects with the TownPass app through two-way connection
Connection Mechanism
As mentioned on the Introduction page, TownPass connects with the App through the web-message-listeners provided by flutter_inappwebview.
The web-message-listeners globally register an object in the webpage for use, and the object's name can be defined through the Flutter part.
- Webpage Calling the App: The webpage sends string information to the App via the
postMessage
method of the object as a means of connection. - Webpage Receiving Messages from the App: The object listens to the App’s call using
onmessage
oraddEventListener
, processing the information coming from the App.
ℹ️ Method Information
postMessage
can only accept one string-type parameter. If the data to be sent to the App is not a string, it must be converted into a string before being passed as a parameter.onmessage
can be assigned a function, which will be passed an event parameter. The information from the App is stored as a string inevent.data
, and further processing ofevent.data
can be done within the function.addEventListener
works just like JavaScript'saddEventListener
. The first parameter receives the event, which is always calledmessage
in this context. When the App sends information, the object will receive the message event.
The second parameter passes in a callback function, which will also be passed an event parameter. You can process event.data within the function.
⚠️ Note
Since the object provided by web-message-listeners exists globally,
when using the addEventListener
method, be mindful of the relationship between the Vue component’s lifecycle and the listener. Use removeEventListener
as needed to remove the listener to avoid creating unintended listeners.
Usage Design in the Project
We have already defined the connection format between the TownPass App and the microservices. The data is uniformly passed as a string-converted object, with the object containing two keys: name and data.
name | data |
---|---|
The category of the data being connected, such as userinfo | The transmitted and received data will be in string form, but the format after parsing is not limited and can also be null |
ℹ️ Reference Information
We have implemented features for obtaining user information from the App and opening the map within the microservice project.
You can refer to the following file paths to learn more about the usage.
/src/views/HomeView.vue
/src/views/HotSpotView.vue
/src/views/TicketDetail.vue
/src/views/CouponDetail.vue
/src/composables/useConnectionMessage.ts
/src/composables/useHandleConnectionData.ts