Developer
WebSocket API
Client Setup

Client Setup

Every example in Commands uses these two helpers: send to run a command, and on to handle its response.

xsoverlay.js
const ws = new WebSocket('ws://localhost:42070/?client=MyApp');
const handlers = {};
 
function send(command, { jsonData, rawData } = {}) {
  ws.send(JSON.stringify({
    target: 'xsoverlay',
    command,
    jsonData: jsonData === undefined ? undefined : JSON.stringify(jsonData),
    rawData,
  }));
}
 
function on(command, handler) {
  handlers[command] = handler;
}
 
ws.addEventListener('message', (event) => {
  const message = JSON.parse(event.data);
  const data = message.jsonData ? JSON.parse(message.jsonData) : null;
  handlers[message.command]?.(data, message.rawData);
});

With those in place, sending a notification and reading the clock looks like this:

ws.addEventListener('open', () => {
  send('SendNotification', { jsonData: { title: 'Hello', content: 'From MyApp', timeout: 5 } });
 
  on('UpdateDateTime', (time) => console.log(time.Time));
  send('RequestDateTime');
});