Tutorial: 11 - Writing OmniScript Plugins

11 - Writing OmniScript Plugins

In certain circumstances it may make sense to limit the amount of traffic between client and server or to obscure certain processes from a client application. In these situations a plugin interface is provided to OmniScript such that you can inject code to handle custom events into OmniScript without needing to be familiar with the internals of OmniScript.

Here's an example plugin:

/**
 * This is an example plugin, it demonstrates how to add a custom event handler
 * in order to handle a custom inbound message.
 */
function ExamplePlugin() {
    this.version = "1.0.0";
    this.name = "Example Plugin";
    this.description = "This is an example plugin, demonstrating how to integrate with OmniScript to add custom events and handlers.";
    this.author = "Michael Powers <mpowers@scriptel.com>";
}
/**
 * This method handles inbound messages from the client.
 * @param message {object} The incoming message from the client.
 * @param connection {WebSocketConnection} The web socket connection to the client.
 * @param state {DeviceState} The state of the device the client is connected to, false if no device leased.
 * @param lease {DeviceLease} Information about the device the client has leased, false if no device leased.
 * @param simulateInput {function} Function that allows you to simulate incoming messages from the client.
 * @return {boolean} True if the inbound message has been handled and should be ignored, false otherwise.
 */
ExamplePlugin.prototype.handleInboundMessage = function(message, connection, state, lease, simulateInput) {
    if(message._class==="ExamplePluginRequest") {
        connection.sendUTF(JSON.stringify({"_class":"ExamplePluginResponse"}));
        return true;
    }
    return false;
};
/**
 * This method handles outbound messages going to the client
 * @param message {object} The outgoing message to the client.
 * @param connection {WebSocketConnection} The web socket connection to the client.
 * @param state {DeviceState} The state of the device the client is connected to, false if no device leased.
 * @param lease {DeviceLease} Information about the device the client has leased, false if no device leased.
 * @param simulateInput {function} Function that allows you to simulate incoming messages from the client.
 * @return {boolean} True if the outbound message has been handled and should be ignored, false otherwise.
 */
ExamplePlugin.prototype.handleOutboundMessage  = function(message, connection, state, lease, simulateInput) {
    return false;
};

//This exposes the plugin to OmniScript.
var example = new ExamplePlugin();
module.exports = example;

Plugins are stored in the lib/plugins directory and follow the naming convention "plugin-*.js". The interface allows plugins to intercept events to and from OmniScript.