@drawbridgesolutions/js-sdk
    Preparing search index...

    Class DrawbridgeConnection

    Manages a persistent WebSocket connection between a screen client and the Drawbridge server.

    Each instance represents one named screen (display panel) in a Drawbridge experience. The connection is established automatically on construction and will reconnect if the server drops the link. Incoming server commands are dispatched to registered callbacks, and outgoing variable updates are sent back over the same socket.

    // Basic setup — connect a screen and react to state changes
    import { DrawbridgeConnection } from "@drawbridgesolutions/js-sdk";

    const connection = new DrawbridgeConnection({
    screen_name: "lobby-display",
    });

    connection.onScreenChange((screen) => {
    console.log("Active screen:", screen);
    });
    // Full lifecycle — connect, react, report results, then disconnect
    import { DrawbridgeConnection } from "@drawbridgesolutions/js-sdk";

    const connection = new DrawbridgeConnection({
    screen_name: "puzzle-terminal",
    });

    connection.onScreenChange((screen) => {
    if (screen === "active") {
    showPuzzle();
    } else {
    hidePuzzle();
    }
    });

    function onPuzzleSolved() {
    connection.setVariable("TERMINAL", "COMPLETE");
    }

    // Tear down when the experience ends
    window.addEventListener("beforeunload", () => connection.close());
    Index

    Constructors

    • Creates a new DrawbridgeConnection and immediately opens a WebSocket to the server.

      The underlying socket uses an auto-reconnect strategy, so transient network interruptions are handled transparently. The connection URL is derived from the provided screen name.

      Parameters

      • options: { screen_name: string }

        Connection configuration.

        • screen_name: string

          Unique identifier for this screen as registered in the Drawbridge project and in playbook settings. Must exactly match the name configured on the server.

      Returns DrawbridgeConnection

      const connection = new DrawbridgeConnection({
      screen_name: "escape-room-screen-1",
      });

    Accessors

    • get getCurrentScreen(): string | null

      The identifier of the most recently received screen, or null if no screen-change command has been received since the connection was opened.

      This value is updated synchronously each time an onScreenChange message arrives, so it always reflects the last known server state. It is safe to read at any time to determine the current screen without waiting for the next event.

      Returns string | null

      // Check the current screen before performing an action
      if (connection.getCurrentScreen === "puzzle-active") {
      enableInputControls();
      }
      // Guard against acting on stale state at init time
      window.addEventListener("focus", () => {
      const screen = connection.getCurrentScreen;
      if (screen !== null) {
      syncUIToScreen(screen);
      }
      });
    • get isConnected(): boolean

      Whether the WebSocket connection to the Drawbridge server is currently open.

      Returns true only when the socket's readyState is OPEN. During the initial connection attempt, a reconnect pause, or after close has been called, this will be false. Calls to setVariable while disconnected will be queued by the underlying ReconnectingWebSocket and sent once the link is restored.

      Returns boolean

      // Show a connection status indicator
      setInterval(() => {
      const indicator = document.getElementById("status-dot")!;
      indicator.className = connection.isConnected ? "dot-green" : "dot-red";
      }, 1000);
      // Conditionally show a warning banner
      if (!connection.isConnected) {
      showBanner("Waiting for server connection…");
      }

    Methods

    • Adds an event listener to the connection's internal EventTarget.

      This follows the standard EventTarget.addEventListener interface and can be used to subscribe to custom events dispatched internally by the SDK, or to fan out connection events to multiple listeners without replacing the primary onScreenChange callback.

      Parameters

      • type: string

        A case-sensitive string identifying the event type to listen for.

      • listener: EventListener

        The handler invoked when a matching event is dispatched.

      • Optionaloptions: boolean | AddEventListenerOptions

        An AddEventListenerOptions object or a boolean useCapture flag, forwarded directly to the underlying EventTarget.

      Returns void

      // Listen for a hypothetical "connected" custom event
      connection.addEventListener("connected", () => {
      console.log("Socket is ready");
      });
      // One-time listener using the options object
      connection.addEventListener("screenReady", () => {
      initializeAnimations();
      }, { once: true });
    • Permanently closes the WebSocket connection to the Drawbridge server.

      After calling close, the auto-reconnect behaviour is disabled and no further messages will be sent or received. This should be called when the screen is unmounted or the page is about to unload to avoid leaving orphaned sockets on the server.

      Returns void

      // Clean up on page unload
      window.addEventListener("beforeunload", () => {
      connection.close();
      });
      // Disconnect when a React component unmounts
      useEffect(() => {
      return () => connection.close();
      }, []);
    • Registers a callback that fires whenever the server sends a screen-change command.

      Only one callback is active at a time — calling onScreenChange again replaces the previous registration. The callback receives the new screen identifier as a string, which maps to a state defined in the Drawbridge project (e.g. "0", "1", "intro").

      The callback also fires on reconnect if the server re-sends the current screen state.

      Parameters

      • callback: CallbackFunction

        Function invoked with the new screen identifier each time the active screen changes. The string value is defined by the Drawbridge project configuration.

      Returns void

      // Switch video content based on the active screen

      connection.onScreenChange((screen) => {
      switch (screen) {
      case "idle":
      showIdleVideo();
      break;
      case "intro":
      showIntroVideo();
      break;
      case "puzzle":
      showPuzzleScreen();
      break;
      default:
      showIdleVideo();
      }
      });
      // Toggle UI visibility based on screen state
      connection.onScreenChange((screen) => {
      const isActive = screen !== "0";
      document.getElementById("overlay")!.style.display = isActive ? "block" : "none";
      });
    • Removes an event listener previously registered via addEventListener.

      The type, listener, and options arguments must match those used when the listener was added, following the same semantics as EventTarget.removeEventListener.

      Parameters

      • type: string

        The event type string that was passed to addEventListener.

      • listener: EventListener

        The exact listener reference that was registered.

      • Optionaloptions: boolean | EventListenerOptions

        The capture flag or options object that was passed when adding the listener.

      Returns void

      function onConnected() {
      console.log("Connected");
      }

      connection.addEventListener("connected", onConnected);

      // Later, stop listening
      connection.removeEventListener("connected", onConnected);
      // Remove a capture-phase listener
      connection.removeEventListener("screenReady", handler, { capture: true });
    • Sends a variable update to the Drawbridge server.

      Variables are the primary mechanism for a screen to report state back to the server — for example, signalling that a puzzle has been solved, submitting an answer, or reporting a numeric score. The server can then use these values to trigger transitions, unlock other screens, or drive game logic.

      If the connection is not currently open, the underlying ReconnectingWebSocket will buffer the message and deliver it once the link is restored.

      Parameters

      • variableName: string

        The name of the variable as defined in the Drawbridge playbook settings. This must match the variable name configured on the server exactly (case-sensitive).

      • value: string | number | boolean

        The new value for the variable. Accepts string, number, or boolean.

      Returns void

      // Report that a puzzle was completed successfully
      connection.setVariable("VAULT_PUZZLE", "DONE");
      // Reset a variable to its default sentinel value after a failed attempt
      connection.setVariable("VAULT_PUZZLE", "-");
      // Send a numeric score
      connection.setVariable("PLAYER_SCORE", 4200);
      // Toggle a boolean flag
      connection.setVariable("LIGHTS_ON", true);
      // Validate a code entry and report pass/fail
      function checkCode(entered: string) {
      const correct = entered === "7734";
      connection.setVariable("KEYPAD_CODE", correct ? "CORRECT" : "WRONG");
      }