Skip to main content
Executes custom commands in the playground, including "setBroadcastToken" and "showVersion". This method provides access to special playground commands that don’t have dedicated SDK methods.

Signature

playground.exec(
  command: "setBroadcastToken" | "showVersion",
  ...args: any[]
): Promise<{ output: any } | { error: string }>

Parameters

command
string
required
The command to execute. Available commands:
  • "setBroadcastToken" - Set a broadcast token for real-time collaboration
  • "showVersion" - Display the LiveCodes version in the console
args
any[]
Variable number of arguments to pass to the command. Required arguments depend on the command being executed.

Returns

result
{ output: any } | { error: string }
A promise that resolves to either:
  • { output: any } - Success response with command output
  • { error: string } - Error response with error message

Available Commands

setBroadcastToken

Sets a broadcast token to enable real-time collaboration and code synchronization across multiple playground instances.

Usage

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

// Set broadcast token for collaboration
const result = await playground.exec("setBroadcastToken", "my-unique-token-123");

if ('output' in result) {
  console.log("Broadcast enabled!");
} else {
  console.error("Error:", result.error);
}

Collaborative Editing Example

import { createPlayground } from "livecodes";

// Create first playground instance
const playground1 = await createPlayground("#container1");

// Create second playground instance
const playground2 = await createPlayground("#container2");

// Use the same token for both to sync them
const token = "collaboration-session-" + Date.now();

await playground1.exec("setBroadcastToken", token);
await playground2.exec("setBroadcastToken", token);

// Now changes in playground1 will appear in playground2 and vice versa!
console.log("Playgrounds are now synchronized");

Room-Based Collaboration

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

// Generate or get a room ID (e.g., from URL params)
const urlParams = new URLSearchParams(window.location.search);
const roomId = urlParams.get('room') || generateRoomId();

// Join the room
const result = await playground.exec("setBroadcastToken", roomId);

if ('output' in result) {
  console.log(`Joined room: ${roomId}`);
  
  // Update URL so others can join the same room
  const shareUrl = `${window.location.origin}${window.location.pathname}?room=${roomId}`;
  document.getElementById('share-link').textContent = shareUrl;
} else {
  console.error("Failed to join room:", result.error);
}

function generateRoomId() {
  return 'room-' + Math.random().toString(36).substring(2, 15);
}

showVersion

Displays the current LiveCodes version in the playground console.

Usage

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

// Show version in playground console
const result = await playground.exec("showVersion");

if ('output' in result) {
  console.log("Version displayed in playground console");
  console.log("Version info:", result.output);
}

Display Version in UI

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

const versionButton = document.getElementById('version-button');

versionButton.addEventListener('click', async () => {
  const result = await playground.exec("showVersion");
  
  if ('output' in result) {
    // Version is also shown in playground console
    // You can also display it in your own UI
    alert(`LiveCodes Version: ${result.output}`);
  }
});

Error Handling

All commands return either a success object with output or an error object with error.
import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

try {
  const result = await playground.exec("setBroadcastToken", "my-token");
  
  if ('error' in result) {
    // Handle error
    console.error("Command failed:", result.error);
    showErrorNotification(result.error);
  } else {
    // Handle success
    console.log("Command succeeded:", result.output);
    showSuccessNotification("Broadcast enabled!");
  }
} catch (error) {
  // Handle unexpected errors
  console.error("Unexpected error:", error);
}

Advanced Examples

Broadcast Server URL

You can customize the broadcast server URL in the playground configuration:
import { createPlayground } from "livecodes";

const playground = await createPlayground("#container", {
  config: {
    // Custom broadcast server (advanced use case)
    // By default uses LiveCodes broadcast server
  },
});

// Then set the broadcast token
await playground.exec("setBroadcastToken", "my-token");

Real-Time Collaboration UI

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

const collaborateButton = document.getElementById('collaborate');
const roomInput = document.getElementById('room-input');
const statusDiv = document.getElementById('status');

collaborateButton.addEventListener('click', async () => {
  const roomId = roomInput.value.trim();
  
  if (!roomId) {
    alert('Please enter a room ID');
    return;
  }
  
  statusDiv.textContent = 'Connecting...';
  
  const result = await playground.exec("setBroadcastToken", roomId);
  
  if ('output' in result) {
    statusDiv.textContent = `Connected to room: ${roomId}`;
    statusDiv.style.color = 'green';
    
    // Watch for code changes from collaborators
    playground.watch('code', ({ code }) => {
      console.log('Code updated (possibly by collaborator)');
    });
  } else {
    statusDiv.textContent = `Error: ${result.error}`;
    statusDiv.style.color = 'red';
  }
});

Debug Information

import { createPlayground } from "livecodes";

const playground = await createPlayground("#container");

const debugButton = document.getElementById('debug');

debugButton.addEventListener('click', async () => {
  // Show version in console
  const versionResult = await playground.exec("showVersion");
  
  // Get config
  const config = await playground.getConfig();
  
  // Get code
  const code = await playground.getCode();
  
  // Compile debug info
  const debugInfo = {
    version: versionResult.output,
    config: {
      mode: config.mode,
      theme: config.theme,
      languages: [
        config.markup.language,
        config.style.language,
        config.script.language,
      ],
    },
    code: {
      markupLength: code.markup.content.length,
      styleLength: code.style.content.length,
      scriptLength: code.script.content.length,
    },
  };
  
  console.log('Debug Info:', debugInfo);
  
  // Copy to clipboard
  await navigator.clipboard.writeText(JSON.stringify(debugInfo, null, 2));
  alert('Debug info copied to clipboard');
});

Notes

  • The exec method is designed for special commands that don’t fit into standard SDK methods.
  • Broadcast functionality requires network connectivity to the LiveCodes broadcast server.
  • When using broadcast, all playground instances with the same token will sync their code changes in real-time.
  • The showVersion command is primarily for debugging and support purposes.
  • If the playground is not yet loaded, calling this method will load it first.
  • Unknown commands will return an error response.

Build docs developers (and LLMs) love