Skip to content

Databridges JavaScript SharedWorker boilerplate code

dataBridges allows you deliver highly responsive real-time user interface to your customer using dataBridges channels along with event bindings.

When your web app has cpu consuming message manipulation such as encyption / decryption, data transformation before sending (publish) or after receiving (bind.channelEvents) real-time data, you can easily use webWorkers to run your JS functions. They are useful because they give you another thread to perform operations in. This can help free up the main thread and keep the app interactive.

dataBridges JavaScript SDK can be easily used inside web workers and supports both dedicated and shared worker.

Download source

GitHub-Mark-32px Source is available in https://github.com/databridges-io/boilerplate.js.webworkers

dataBridges as dedicated workers

You will use dedicated workers if your app is a single instance app or each app page interface is completely independent from other (for example duplicating the running browser tab for example is not supported in your application).

We have developed a ready to use dbridge-dedicatedWorker.js boilerplate code for your usage.

dataBridges as shared workers

Shared workers are special web workers that can be accessed by multiple browser contexts like browser tabs, windows, iframes, or other workers, etc. All browser contexts must be within the same domain in accordance with the same-origin policy.

The difference between dedicated and shared workers is that dedicated workers can only be accessed by one script. Shared workers can be accessed by multiple scripts even if each page run inside different windows.

you will use shared worker if your app supports multiple browser tabs, windows, iframes and each of them consumes a global state updated by your application server using dataBridges channels or client functions.

We have developed a ready to use dbridge-sharedWorker.js boilerplate code for your usage.

Explaining the boilerplate code.

Usage Overview

The following topics are covered:

Supported platforms

Safari Firefox Chrome Edge Opera Firefox(Android)
16+ 29+ 4+ 79+ 10.6+ 33+

Initialization

Just start the dataBridges SharedWorker JavaScript file into your JavaScript code as shown below.

dbSharedWorker = new SharedWorker("dbridgesSharedWorker.js");

You need to replace appkey and auth_url with the actual URL and Application Key in the dbridgesSharedWorker.js file in below section.

// Replace your dataBrdiges Application Key and Authentication URL below.
const dbApplnKey = 'appkey';
const dbAuthURL = 'auth_url';
Properties Description
auth_url (string) Authentication url from dataBridges dashboard.
appkey (string) Application Key from dataBridges dashboard.

How to Use

To make the coding readable we will be using below structure. This will be used for defining both sending and receiving messages from and to Shared Workers. Each event types will have different sets of parameters along with the event types.

NOTE : You can enhance dbridgesSharedWorker.js this file depending on your requirement. This file helps you get started with basic functionality of dataBridges network library.

const workerEvents = {
    subscribe: 1,
    publish: 2,
    unsubscribe: 3,
    channelList: 4,
    closing: 5,
    dbStatus: 11,
    dbLog: 12,
    clientLength: 13,
    session: 15,
    event: 16,
    logout: 17
}
Define event handling for Shared Worker, This is the code which receives events from dbSharedWorker.js.

You need to store workerSessionId in a global variable and should be used while sending any message to dbSharedWorker.js, This is the first event which will be received once you initiate the dbSharedWorker.js using new SharedWorker("dbridgesSharedWorker.js")

dbSharedWorker.port.onmessage = function (e) {
    const recdData = e.data;
    switch (recdData.cmd) {
        case workerEvents.dbStatus:
            // Databridge connection status.
            // recdData.msg will have dataBridges Offline/Online status whenever they are changed
            console.log('dataBridges Connection Status :',recdData.msg);
            break;
        case workerEvents.session:
            // SessionId recieved from SharedWorker
            // Assign workerSessionId to a global variable which can be used later with every call to dbSharedWorker
            workerSessionId = recdData.data;
            break;
        case workerEvents.dbLog:
            // Log messages recieved from SharedWorker
            // Logs on dataBridges Events and other errors if any as and when generated.
            console.log(recdData.msg, recdData.err != '' ? 'Error : ' + recdData.err:'');
            break;
        case workerEvents.clientLength:
            // Connected Client Length received from SharedWorker
            // Number of browser connects connected to SharedWorker. 
            console.log('# Browser Connects :',recdData.msg);
            break;
        case workerEvents.channelList:
            // Client List received from SharedWorker
            // List of channels subscirbed by current browser connect. The result is comma seperated.
            console.log('Channels Subscribed :',recdData.msg);
            break;
        case workerEvents.event:
            // Data Event received from dataBridges Event listner.
            // Pubished events with data received by dataBridges on the Subscribed channel by this browser connect.
            console.log('Event Received :', recdData.eventname,'Payload', recdData.payload,'MetaData :',JSON.stringify(recdData.metadata));
            break;
        default:
            break;
    }
};
Add an event browser event listener for 'beforeunload' to make sure Shared worker is duly informed about closure of your browser instance.

// addeventlistener to capture onclose events and sent the close command to the shared worker
addEventListener('beforeunload', function () {
    if (workerSessionId) {
        dbSharedWorker.port.postMessage({
            cmd: workerEvents.closing,
            sessionid: workerSessionId
        });
    }
});

Subscribing to Channel

To subscribe to a channel and listen to an event send a message to dbSharedWorker with below parameters. Replace Channel_Name and Event_Name with your Channel Name and Event Name

if (workerSessionId) {
    dbSharedWorker.port.postMessage({
        cmd: workerEvents.subscribe,
        sessionid: workerSessionId,
        data: {
            channel: 'Channel_Name',
            event: 'Event_Name'
        }
    })
}

Unsubscribe from channel

To Unsubscribe from a channel send a message to dbSharedWorker with below parameters. Replace Channel_Name with your Channel Name.

if (workerSessionId) {
    dbSharedWorker.port.postMessage({
        cmd: workerEvents.unsubscribe,
        sessionid: workerSessionId,
        data: {
            channel: 'Channel_Name'
        }
    })
}

Subscribed channel list

To get list of all subscribed channels send a message to dbSharedWorker with below parameters.

if (workerSessionId) {
    dbSharedWorker.port.postMessage({
        cmd: workerEvents.channelList,
        sessionid: workerSessionId
    })
}

Publish events to channel

To publish an event to a channel send a message to dbSharedWorker with below parameters. Replace Channel_Name ,Event_Name and Payloadwith your Channel Name , Event Name and Payload

if (workerSessionId) {
    dbSharedWorker.port.postMessage({
        cmd: workerEvents.publish,
        sessionid: workerSessionId,
        data: {
            channel: 'Channel_Name',
            event: 'Event_Name',
            payload: 'Payload'
        }
    })
}

Trust Tokens Implementation

While working with Private,Presence or System channel, you need to implement Trust Tokens. There is a function defined in dbSharedWorker.js which you can modify to get your own trust token implementation. If you want to use the same functionality, you need to expose /token route in your server and expose the trust token creation functionality.

// Get access token when channel is private,presence  or system.
const getAccessToken = (payloadJson, res, clientSessionId) => {
    fetch('/token', {
        method: 'POST',
        headers: {
            Accept: 'application.json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payloadJson)
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not OK');
        }
        return response.json();
    }).then(data => {
        res.end(data);
    }).catch(err => {
        clients[clientSessionId].postMessage({
            cmd: workerEvents.dbLog,
            msg: 'dataBridges getAccessToken exception..',
            err: err.source + ',' + err.code + ',' + err.message
        });
        res.end({
            statuscode: 1,
            error_message: error.message,
            accesskey: ''
        });
    });
}