App State Sync
It is important that you maintain the state of your application, see OmniStream State for more information. You can then use the OmniStream Sync library to sync your state between multiple users in different browsers.
Host - Selects which Guests to share state with and controls the sessions state
Guest - registers itself with the service and receives all state
You can have multiple guest's controlled by a single Host. Hosts and Guests may also register listeners to send and receive custom messages in addition to the state object.
Setup
- Include the OmniStream Session Sync
<script
src="https://omnistreamsync.app-platform.zlthunder.net/omnistream-session-sync.js"
defer
></script>
- If using built in UI components e.g. Guest List (for selecting and de-selecting guests), create an element to pass to the init call
<div id="zl-ui-container"></div>
- Initialize the library, this should be done on both the host and guest page
const params = {
user: {
type: "host", //set to "guest" for your guests
},
oemID: "example", //unique ID for your service (must be the same on your guest and host page)
ui: {
on: true,
parentId: 'zl-ui-container'
},
offline: false,
mqtt: {
options: {
userName: [ask your account manager],
password: [ask your account manager],
},
},
};
console.log(params);
window.sessionSync.init(params);
Your Host and Guest pages must be hosted on the same Domain as the URL is used to build a unique oemID. The value you pass into oemID could be a URL param to make it easy to pair a single host and guest in a unique session.
- Add event listener
document.addEventListener("state_changed", (event) => {
console.log("state_changed", event.detail);
sendJsonData(event.detail);
});
- Where you would send state over cloudstream.sendJsonData(data), you should now set the state to window.sessionSync.host.state
function sendJsonData(data) {
if (window.cloudstream) {
window.cloudstream.sendJsonData(data);
}
}
function setAppState(data) {
if (window.sessionSync && window.sessionSync.host) {
window.sessionSync.host.state = {
...window.sessionSync.host.state,
...data,
};
} else {
sendJsonData(data);
}
}
- Both the Host and all Guests will receive the state_changed event which should then be passed into cloudstream.sendJsonData(data)
:::
Custom Events
You may also send and receive custom events and data between all participants. In the following example, we want the host to receive the "guest_name" event.
In our 'host' web application, we'll add the following listener.
document.addEventListener("guest_name", (event) => {
console.log("guest_name", event.detail);
});
In our guest web application, we'll execute the following method
window.sessionSync.guest.send("guest_name", {"name":"peter"} );
On your hosts browser console you'll see the following. Note the inclusion of the clientId which is a unique identifier added automatically for your connected host and guests.
guest_name
{name: 'Peter', clientId: 'XXXXXXXXX_ZL'}