How to detect if a web app is running in Electron

Viewed 1231

I'm trying to serve real react app on electron app. It doesn't mean I'm developing electron app with react. I've created a react app and injected it into electron app. (Like slack, it will serve as a web application and desktop application.) But I'm confused that send desktop notifications.

Now the main question is: How can I get the application type. I mean, is user using my app on web or on desktop. How can I get this?

Thank you :)

1 Answers

There are many ways to detect whether you are running in a desktop environment or not.

You can check the User-Agent and you can set the userAgent value in Electron when you call loadURL.

Another way is declaring a global variable using a preload script.

// main process
new BrowserWindow({
  webPreferences: {
    preload: "preload.js",
  },
});

// preload.js 
// you don't need to use contextBridge if contextIsolation is false
// but it's true by default in Electron 12
const { contextBridge } = require("electron"); 
contextBridge.exposeInMainWorld("IN_DESKTOP_ENV", true);

// renderer process (your React world)
if (globalThis.IN_DESKTOP_ENV) {
  // do something...
}

enter image description here

Related