The Playground object returned by createPlayground provides a comprehensive API for controlling and interacting with the embedded playground.
Overview
All methods return Promises and should be awaited:
const playground = await createPlayground ( '#container' );
await playground . run ();
load
Loads the playground if not already loaded.
Description
When the embed option loading is set to "click", the playground shows a “Click to load” screen. This method programmatically loads the playground.
If the playground is already loaded, this method does nothing. If any other method is called before the playground loads, it will automatically trigger loading first.
Example
const playground = await createPlayground ( '#container' , {
loading: 'click' ,
template: 'react' ,
});
// Later, load the playground
await playground . load ();
run
Runs the result page after compiling the code.
Description
Compiles the code from all editors and displays the result page. This is equivalent to clicking the “Run” button in the UI.
Example
const playground = await createPlayground ( '#container' , {
config: {
markup: { language: 'html' , content: '<h1>Hello</h1>' },
},
});
await playground . run ();
// Result page now displays the compiled code
Use Cases
Auto-run when playground is ready
Run after updating configuration
Manual run triggers
playground . watch ( 'ready' , async () => {
await playground . run ();
});
Formats the code in the editors.
format ( allEditors ?: boolean ): Promise < void >
Parameters
If true, formats all editors. If false, formats only the active editor.
Description
Formats the code using the configured formatter (Prettier). Respects the formatter settings in the configuration.
Example
// Format all editors
await playground . format ();
// Format only active editor
await playground . format ( false );
getShareUrl
Generates a share URL for the current project.
getShareUrl ( shortUrl ?: boolean ): Promise < string >
Parameters
If true, generates a short URL. If false, returns a long URL with encoded config.
Returns
The share URL for the current project.
Description
By default, returns a URL with the configuration encoded in the query string. If shortUrl is true, generates a short URL that redirects to the full URL.
Example
const playground = await createPlayground ( '#container' , {
template: 'react' ,
});
// Get long URL
const longUrl = await playground . getShareUrl ();
console . log ( longUrl );
// https://livecodes.io/#config=code/N4Ig...
// Get short URL
const shortUrl = await playground . getShareUrl ( true );
console . log ( shortUrl );
// https://livecodes.io/s/abc123
getConfig
Gets the current configuration object.
getConfig ( contentOnly ?: boolean ): Promise < Config >
Parameters
If true, returns only content-related configuration (code, title, description, etc.). If false, returns the complete configuration including user settings.
Returns
The current configuration object.
Description
Retrieves the playground state as a configuration object. This can be used to save state, export projects, or restore state later.
Example
const playground = await createPlayground ( '#container' , {
template: 'javascript' ,
});
// Get full config
const fullConfig = await playground . getConfig ();
console . log ( fullConfig . theme ); // 'dark' or 'light'
console . log ( fullConfig . autoupdate ); // true or false
// Get content only
const contentConfig = await playground . getConfig ( true );
console . log ( contentConfig . markup . content );
console . log ( contentConfig . script . content );
// Save to localStorage
localStorage . setItem ( 'project' , JSON . stringify ( contentConfig ));
setConfig
Loads a new configuration.
setConfig ( config : Partial < Config > ): Promise < Config >
Parameters
The configuration object to load. Can be a partial configuration - only specified properties will be updated.
Returns
The resulting configuration after the update.
Description
Updates the playground with a new configuration. This can modify code, settings, languages, and more. The configuration is merged with existing config.
Example
const playground = await createPlayground ( '#container' );
// Load new code
const newConfig = await playground . setConfig ({
markup: {
language: 'markdown' ,
content: '# Hello World' ,
},
style: {
language: 'css' ,
content: 'body { padding: 2rem; }' ,
},
autoupdate: true ,
});
console . log ( 'Config updated:' , newConfig );
Use Cases
// Load from saved state
const saved = JSON . parse ( localStorage . getItem ( 'project' ));
await playground . setConfig ( saved );
// Update just the script
await playground . setConfig ({
script: {
language: 'typescript' ,
content: 'const x: number = 42;' ,
},
});
// Change theme
await playground . setConfig ({
theme: 'dark' ,
});
getCode
Gets the code from all editors and the result page.
Returns
An object containing the source code, language, and compiled code for each editor, plus the result HTML.
Description
Retrieves the code from all three editors (markup, style, script) along with their compiled versions and the result page HTML.
Example
const playground = await createPlayground ( '#container' , {
template: 'react' ,
});
const code = await playground . getCode ();
console . log ( 'Markup:' , code . markup );
// { language: 'html', content: '...', compiled: '...' }
console . log ( 'Style:' , code . style );
// { language: 'css', content: '...', compiled: '...' }
console . log ( 'Script:' , code . script );
// { language: 'jsx', content: '...', compiled: '...' }
console . log ( 'Result HTML:' , code . result );
// Full HTML of the result page
Code Interface
interface Code {
markup : {
language : Language ;
content : string ; // Source code
compiled : string ; // Compiled code
};
style : {
language : Language ;
content : string ;
compiled : string ;
};
script : {
language : Language ;
content : string ;
compiled : string ;
};
result : string ; // Result page HTML
}
show
Shows or focuses a specific panel.
show (
panel : EditorId | 'editor' | 'result' | 'toggle-result' | ToolName ,
options ?: ShowOptions
): Promise < void >
Parameters
The panel to show. Can be:
"markup", "style", "script" - Show specific editor
"editor" - Show editor pane
"result" - Show result pane
"toggle-result" - Toggle result pane visibility
"console", "compiled", "tests" - Show specific tool
Additional options:
full (boolean): Show in full screen
line (number): Line number to scroll to (for editors)
column (number): Column number (for editors)
zoom (1 | 0.5 | 0.25): Zoom level (for result)
Example
// Show style editor
await playground . show ( 'style' );
// Show result in full screen
await playground . show ( 'result' , { full: true });
// Show script editor at specific line
await playground . show ( 'script' , { line: 42 , column: 10 });
// Show console tool
await playground . show ( 'console' );
// Toggle result visibility
await playground . show ( 'toggle-result' );
// Show result with zoom
await playground . show ( 'result' , { zoom: 0.5 });
runTests
Runs the project tests and returns results.
runTests (): Promise < { results : TestResult [] } >
Returns
object
{ results: TestResult[] }
An object containing an array of test results.
Description
Executes the tests defined in the project and returns the results. Requires tests to be configured in the project.
Example
const playground = await createPlayground ( '#container' , {
config: {
script: {
language: 'javascript' ,
content: 'export const add = (a, b) => a + b;' ,
},
tests: {
language: 'javascript' ,
content: `
import { add } from './script';
import { test, expect } from '@jest/globals';
test('adds numbers', () => {
expect(add(1, 2)).toBe(3);
});
` ,
},
},
});
const { results } = await playground . runTests ();
results . forEach ( result => {
console . log ( 'Test:' , result . testPath . join ( ' > ' ));
console . log ( 'Status:' , result . status ); // 'pass', 'fail', or 'skip'
console . log ( 'Duration:' , result . duration , 'ms' );
if ( result . errors . length > 0 ) {
console . error ( 'Errors:' , result . errors );
}
});
TestResult Interface
interface TestResult {
duration : number ; // Test duration in ms
errors : string []; // Error messages
status : 'pass' | 'fail' | 'skip' ;
testPath : string []; // Test path (e.g., ['describe', 'test name'])
}
watch
Watches for playground events.
watch (
event : 'load' | 'ready' | 'code' | 'console' | 'tests' | 'destroy' ,
callback : ( data ?: any ) => void
): { remove : () => void }
See the Events documentation for detailed information about all available events.
Quick Example
// Watch for code changes
const watcher = playground . watch ( 'code' , ({ code , config }) => {
console . log ( 'Code changed!' );
});
// Remove watcher
watcher . remove ();
exec
Executes custom commands.
exec ( command : string , ... args : any []): Promise < { output : any } | { error : string } >
Parameters
The command to execute. Available commands:
"setBroadcastToken" - Set token for broadcasting
"showVersion" - Show LiveCodes version
Arguments for the command.
Returns
result
{ output: any } | { error: string }
Result object with either output or error.
Example
// Show version
const version = await playground . exec ( 'showVersion' );
console . log ( 'LiveCodes version:' , version . output );
// Set broadcast token
await playground . exec ( 'setBroadcastToken' , 'your-token-here' );
destroy
Destroys the playground and cleans up resources.
Description
Removes the playground iframe, cleans up event listeners, and releases resources. After calling destroy(), no other SDK methods can be called on this instance.
Example
const playground = await createPlayground ( '#container' , {
template: 'javascript' ,
});
// Use the playground...
// Clean up when done
await playground . destroy ();
// This will throw an error:
// await playground.run(); // Error: Cannot call API methods after calling destroy()
Use Cases
// React cleanup
useEffect (() => {
createPlayground ( '#container' ). then ( setPlayground );
return () => {
playground ?. destroy ();
};
}, []);
// Vue cleanup
onUnmounted (() => {
playground . value ?. destroy ();
});
// Svelte cleanup
onDestroy (() => {
playground ?. destroy ();
});
onChange (Deprecated)
Deprecated: Use watch('code', callback) instead.
onChange ( callback : ( data : { code : Code ; config : Config }) => void ): { remove : () => void }
This method is deprecated in favor of the more flexible watch method.
// ❌ Old way (deprecated)
playground . onChange (({ code , config }) => {
console . log ( 'Changed' );
});
// ✅ New way
playground . watch ( 'code' , ({ code , config }) => {
console . log ( 'Changed' );
});
Method Chaining
Most methods can be chained using async/await:
const playground = await createPlayground ( '#container' , {
template: 'javascript' ,
});
await playground
. setConfig ({
script: { content: 'console.log("Hello");' },
})
. then (() => playground . run ())
. then (() => playground . format ())
. then (() => playground . getShareUrl ())
. then ( url => console . log ( 'Share URL:' , url ));
Error Handling
All methods return Promises that can reject. Always handle errors:
try {
await playground . run ();
} catch ( error ) {
console . error ( 'Failed to run:' , error );
}
// Or with .catch()
playground . run (). catch ( error => {
console . error ( 'Failed to run:' , error );
});
Next Steps
Events Learn about the event system
Types Browse TypeScript type definitions
API Reference Review the complete API reference
Getting Started Back to getting started guide