1. Windows
  2. Communicating between windows

Windows

Communicating between windows

ToDesktop supports sending messages between multiple windows. Windows that share a domain can use the browser's Broadcast Channel API, while windows with different domains can use ToDesktop's Inter-Process Communication (IPC) Plugin.

Windows that share a domain

The Broadcast Channel API allows basic communication between different windows that share the same origin. If your desktop app windows share the same root URL, then you can use BroadcastChannel to facilitate communication between them.

The following example focuses the window when it receives a message:

        import { nativeWindow } from '@todesktop/client-core';

function onBroadcastChannel(subject, callback) {
  const channel = new BroadcastChannel(subject);
  channel.onmessage = (event) => callback(event.data);

  return () => {
    channel.close();
  };
}

function sendBroadcastMessage(subject, data) {
  const channel = new BroadcastChannel(subject);
  channel.postMessage(data);
  channel.close();
}

// window 1 receives a message from window 2
const unsubscribe = onBroadcastChannel('focus-window', (data) => {
  if (data.shouldFocus) nativeWindow.focus(); // focuses the current window
});

// ...

// window 2 sends a message to window 1
sendBroadcastMessage('focus-window', { shouldFocus: true });

      

Windows that have different domains

If your windows are on a different domain, you can use ToDesktop's IPC Plugin to facilitate communication. This requires installing both the plugin and the @todesktop/client-ipc library (as detailed in the link).

You can then do the following to replicate our window focusing example:

        import { subscribe, publish } from '@todesktop/client-ipc';

// window 1 receives a message from window 2
const unsubscribe = subscribe('focus-window', (data) => {
  if (data.shouldFocus) nativeWindow.focus(); // focuses the current window
});

// ...

// window 2 sends a message to window 1
publish('focus-window', { shouldFocus: true });