Electron js use desktopCapture outside main.js

2.6k views Asked by At

I have an app where I need to capture the Desktop on Button click. All relevent tutorials on YouTube are 1-2 years old. The desktopCapturer module is only available in main component, and I cannot figure out how to use it from there to capture the button click and start recording. Earlier the desktopCapturer module was also available in render component, as I have heard, but now it is only available on main component.

1

There are 1 answers

0
Shai On

check this out: https://www.electronjs.org/docs/latest/api/desktop-capturer

you can trigger a desktop capturing by sending an ipc message from your renderer process (using invoke / async send and on events) to your main process.

The following example will capture your Electron application window:

  1. in your main process:
ipcMain.handle('get-sources', () => {
 return desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => {
   for (const source of sources) {
     if (source.name === 'YOUR ELECTRON APP NAME' && mainWindow) {
       return source.id;
     }
   }
 })
});
  1. in your web application (renderer process):
  const handleStream = (stream: any) => {
      const video = document.querySelector('video')
      video!.srcObject = stream
      video!.onloadedmetadata = () => video!.play()
    }

    const handleError = (e: any) => {
      console.log(e)
    }

    const getResource = async () => {
      const sourceId = await window.electron.getSources();
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: false,
          video: {
            mandatory: {
              chromeMediaSource: 'desktop',
              chromeMediaSourceId: sourceId,
              minWidth: 1280,
              maxWidth: 1280,
              minHeight: 720,
              maxHeight: 720
            }
          }
        })
        handleStream(stream)
      } catch (e) {
        handleError(e)
      }
    }

    getResource();
  1. make sure you have a video html tag in your DOM:
      <video width="750" height="500" controls >
        <source src="" type="video/mp4"/>
      </video>
  1. don't forget to update your preload files in both your electron and webapp. for example:
declare global {
  interface Window {
    electron: {
      getSources: () => Promise<string>,
    };
  }
}

and in electron

contextBridge.exposeInMainWorld('electron', {
  getSources: () => ipcRenderer.invoke('get-sources'),
});