Last updated

PluginBridge Communication

The PluginBridge is a crucial component provided by the @jtl/platform-plugins-core package. Its primary function is to establish a secure and reliable communication channel between your plugin's frontend (running within an Iframe) and the host JTL cloud service environment (e.g., JTL-Wawi).

This bridge allows your plugin to interact with the host environment, request data (like session tokens), and trigger actions specific to the context it's running in.

PluginBridge Interface

The PluginBridge class provides the following methods:

export default class PluginBridge {
    constructor(messagePort: MessagePort);
    // Listen for specific events from the host environment and execute the callback when they occur
    subscribe(event: string, callback: (data: unknown) => Promise<unknown>): void;
    
    // Send data to the host environment under a specific topic, notifying it about actions or state changes
    publish<TPayload>(topic: string, payload: TPayload): Promise<void>;
    
    // Make a plugin function available to be called directly by the host environment
    exposeMethod<TMethod>(methodName: string, method: TMethod): void;
    
    // Check if a specific function has already been exposed to the host environment
    isMethodExposed(methodName: string): boolean;
    
    // Invoke functions provided by the host environment to execute host-specific actions
    callMethod<TResponse>(methodName: string, ...args: unknown[]): Promise<TResponse>;
}

Using PluginBridge Communication Methods

Initializing the PluginBridge

To use the PluginBridge in your React components, you'll need to initialize it and maintain its instance in your component's state. Typically, this is done within a useEffect hook:

import { createPluginBridge, PluginBridge } from '@jtl/platform-plugins-core';
import { useState, useEffect } from 'react';

function YourPluginComponent() {
    // Store the PluginBridge instance in component state
    const [pluginBridge, setPluginBridge] = useState<PluginBridge | undefined>(undefined);

    useEffect((): void => {
        console.log('[HelloWorldPlugin] createPluginBridge...');
        createPluginBridge().then(bridge => {
            console.log('[HelloWorldPlugin] bridge created!');
            // Store the bridge instance in state for use throughout your component
            setPluginBridge(bridge);
        });
    }, []);

    // Rest of your component...
}

The initialization process:

  1. Import the necessary functions from @jtl/platform-plugins-core
  2. Create a state variable to hold the PluginBridge instance
  3. Use createPluginBridge() to establish the connection with the host
  4. Once the bridge is created, you can immediately start calling methods or pass it down to child components.
  5. Store the bridge instance in your component's state for later use

The empty dependency array [] ensures that the effect runs only once when the component mounts.

Subscribe to Host Events

The subscribe method allows your plugin to listen for specific events emitted by the host environment.

// Listen for inventory updates
pluginBridge.subscribe("inventory:updated", async (data) => {
  console.log("Inventory updated:", data);
  return { status: "processed" };
});

When the host system triggers an "inventory:updated" event, your callback function will execute with the provided data.

Publish Messages to the Host

The publish method sends data to the host environment under a specific topic.

// Notify the host about completed action
await pluginBridge.publish("order:verification:complete", {
  orderId: "ORD-12345",
  verifiedBy: "plugin-user"
});

This is useful for informing the host about state changes or actions completed within your plugin.

Expose Methods to the Host

The exposeMethod function makes your plugin's functions callable by the host environment.

// Make a function available to the host
pluginBridge.exposeMethod("calculateShippingCost", (weight, destination) => {
  const baseCost = 5.99;
  const zoneRate = destination === "international" ? 2.5 : 1;
  return baseCost + (0.1 * weight * zoneRate);
});

This allows the host environment to directly use functionality implemented in your plugin.

Check if Method is Exposed

The isMethodExposed method verifies if a specific function has already been exposed to the host.

// Check if a method is already exposed
if (!pluginBridge.isMethodExposed("calculateTax")) {
  pluginBridge.exposeMethod("calculateTax", (amount, rate) => {
    return amount * (rate / 100);
  });
}

This helps prevent errors from attempting to expose the same method multiple times.

Call Host Methods

The callMethod function allows your plugin to invoke functions provided by the host environment.

// Get user information
const userProfile = await pluginBridge.callMethod("getUserProfile");

// Call a method with parameters
const orderDetails = await pluginBridge.callMethod("getOrderDetails", "ORD-5678");

This enables your plugin to access host functionality, data, and services.

Communication Flow

The connection facilitates a two-way communication path: your plugin's pluginBridge instance talks to the corresponding hostPluginBridge instance within the JTL cloud service.

Plugin Frontend (in Iframe)pluginBridge (Instance)hostPluginBridge (Instance)JTL Cloud Service (Setup/ERP)Later InteractionsInitialize (createPluginBridge())Establish ConnectionConnection ReadyBridge Instance ReadycallMethod("methodName", args...)Invoke methodName(args...)Execute Host LogicReturn ResultForward ResultReturn ResultPlugin Frontend (in Iframe)pluginBridge (Instance)hostPluginBridge (Instance)JTL Cloud Service (Setup/ERP)

Creating a PluginBridge Instance

To establish communication with the host environment, you need to create a PluginBridge instance:

import { createPluginBridge, PluginBridge } from '@jtl/platform-plugins-core';
  
const [pluginBridge, setPluginBridge] = useState<PluginBridge | undefined>(undefined);

useEffect((): void => {
  console.log('[HelloWorldPlugin] createPluginBridge...');
  createPluginBridge().then(bridge => {
    console.log('[HelloWorldPlugin] bridge created!');
    setPluginBridge(bridge);
  });
}, []);

Environment-Specific Methods

The PluginBridge exposes different methods depending on which environment your plugin is running in:

Setup Environment Methods

MethodParametersDescription
testargs: stringSimple test method that logs arguments to console
test2msg: string, age: numberTest method with multiple parameters
setupcompletedNoneUpdates the plugin's status to "active" in the hub
getSessionTokenNoneReturns the current session token

ERP Environment Methods

MethodParametersDescription
getCurrentTimeNoneReturns the current time as a Date object
getSessionTokenNoneReturns the current session token

Calling Methods

To call methods exposed by the host environment, use the callMethod function:

// Basic syntax
pluginBridge.callMethod("methodName", parameter1, parameter2, ...);

// Example: Getting a session token
const sessionToken = await pluginBridge.callMethod("getSessionToken");

Session Token Usage

For more detailed information about working with session tokens in your plugin, please refer to our Session Token documentation. This guide explains how to properly use the token for authentication, and token lifecycle management.