electron#app JavaScript Examples

The following examples show how to use electron#app. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: application.js    From razer-macos with GNU General Public License v2.0 6 votes vote down vote up
createTray() {
    if (!this.isDevelopment) {
      if (this.app.dock) {
        this.app.dock.hide();
      }

      if (this.tray != null) {
        this.tray.destroy();
      }
    }

    // Template.png will be automatically inverted by electron: https://www.electronjs.org/docs/api/native-image#template-image
    this.tray = new Tray(path.join(__static, '/assets/iconTemplate.png'));
    this.tray.setToolTip('Razer macOS menu');
    this.tray.on('click', () => {
      if(this.razerApplication.deviceManager.activeRazerDevices != null) {
        this.razerApplication.deviceManager.activeRazerDevices.forEach(device => {
          if (device !== null) {
            device.refresh();
          }
        });
      }
      this.refreshTray();
    });

    this.refreshTray(true);
  }
Example #2
Source File: electron-main.dev.js    From quasar-manage with MIT License 6 votes vote down vote up
app.whenReady().then(() => {
  // allow for a small delay for mainWindow to be created
  setTimeout(() => {
    // Install `electron-debug` with `devtron`
    electronDebug({ showDevTools: false })

    // Install vuejs devtools
    installExtension(VUEJS_DEVTOOLS)
      .then(name => {
        console.log(`Added Extension: ${name}`)
        // get main window
        const win = BrowserWindow.getFocusedWindow()
        if (win) {
          win.webContents.on('did-frame-finish-load', () => {
            win.webContents.once('devtools-opened', () => {
              win.webContents.focus()
            })
            // open electron debug
            console.log('Opening dev tools')
            win.webContents.openDevTools()
          })
        }
      })
      .catch(err => {
        console.log('An error occurred: ', err)
      })
  }, 250)
})
Example #3
Source File: background.js    From melvor-mod-manager with MIT License 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }

  ipcMain.handle('process', processHandler);
  ipcMain.handle('file', fileHandler);
  ipcMain.handle('mods', modsHandler);

  createWindow();
});
Example #4
Source File: index.js    From FreeTube-Vue with GNU Affero General Public License v3.0 6 votes vote down vote up
function setMenu () {
  if (process.platform === 'darwin') {
    template.unshift({
      label: app.getName(),
      submenu: [
        { role: 'about' },
        { type: 'separator' },
        { role: 'services' },
        { type: 'separator' },
        { role: 'hide' },
        { role: 'hideothers' },
        { role: 'unhide' },
        { type: 'separator' },
        { role: 'quit' }
      ]
    })

    template.push({
      role: 'window'
    })

    template.push({
      role: 'help'
    })

    template.push({ role: 'services' })
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}
Example #5
Source File: main.js    From ioHookElectronWebpack with MIT License 6 votes vote down vote up
app.on("ready", async () => {
  try {
    globalShortcut.register('Control+Shift+I', () => {
      if (mainWindow.webContents.isDevToolsOpened()) {
        mainWindow.webContents.closeDevTools()
      } else {
        mainWindow.webContents.openDevTools();
      }
    });

    //protocol.interceptFileProtocol('file', (request, callback) => {
      //const url = request.url.substr(7)    /* all urls start with 'file://' */
      //callback({ path: path.normalize('${__dirname}/${url}')})
    //});

    // Name the protocol whatever you want
    const protocolName = 'safe-file-protocol';

    // NEEDED FOR PROPER IMAGES LOADING
    protocol.registerFileProtocol(protocolName, (request, callback) => {
      const url = request.url.replace(`${protocolName}://`, '');
      try {
        return callback(decodeURIComponent(url))
      } catch (error) {
        // Handle the error as needed
        log.error(error)
      }
    });

    createWindow();
  } catch (error) {
    log.error(error);
    ioHook.stop();
    app.quit();
  }
});
Example #6
Source File: controller.js    From juggernaut-desktop with MIT License 6 votes vote down vote up
/**
   * terminate - Terminate the app.
   */
  terminate() {
    mainLog.debug('terminate...');
    // Send a message to the renderer process telling it to to gracefully shutdown. We register a success callback with
    // it so that we can complete the termination and quit electon once the app has been fully shutdown.
    ipcMain.on('terminateAppSuccess', () => app.quit());

    ipcMain.on('terminateAppFailed', (event, e) => {
      mainLog.info('terminateAppFailed: %o', e);
      this.killAllSpawnedProcesses();
      app.quit();
    });

    this.sendMessage('terminateApp');
  }
Example #7
Source File: main.dev.js    From NoteMaster with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add event listeners...
 */
app.on('window-all-closed', () => {
  // Unregister all shortcuts.
  globalShortcut.unregisterAll();

  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
Example #8
Source File: background.js    From cesium-vue-electron with MIT License 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // Devtools extensions are broken in Electron 6.0.0 and greater
    // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
    // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
    // If you are not using Windows 10 dark mode, you may uncomment these lines
    // In addition, if the linked issue is closed, you can upgrade electron and uncomment these lines
    // try {
    //   await installVueDevtools()
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }
  }
  createWindow()
})
Example #9
Source File: memocast.js    From Memocast with MIT License 6 votes vote down vote up
export default function (keybindings) {
  return {
    label: 'Memocast',
    submenu: [{
      label: i18n.t('aboutMemocast'),
      click () {
        app.showAboutPanel()
      }
    }, {
      type: 'separator'
    }, {
      label: i18n.t('services'),
      role: 'services',
      submenu: []
    }, {
      type: 'separator'
    }, {
      label: i18n.t('hideMemocast'),
      accelerator: keybindings.getAccelerator('mc.hide'),
      role: 'hide'
    }, {
      label: i18n.t('hideOthers'),
      accelerator: keybindings.getAccelerator('mc.hide-others'),
      role: 'hideothers'
    }, {
      label: i18n.t('showAll'),
      role: 'unhide'
    }, {
      type: 'separator'
    }, {
      label: i18n.t('quitMemocast'),
      accelerator: keybindings.getAccelerator('mc.quit'),
      click: app.quit
    }]
  }
}
Example #10
Source File: get-debug-info.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
ipcMain.handle('get-debug-info', () => ({
  version: version,
  env: process.env.NODE_ENV || 'development',
  platform: process.platform,
  arch: process.arch,
  electron: process.versions.electron,
  // !! converts `undefined` reported in Linux to false.
  runningUnderTranslation: !!app.runningUnderARM64Translation
}));
Example #11
Source File: background.js    From mogollar with MIT License 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})
Example #12
Source File: background.js    From dev-sidecar with Mozilla Public License 2.0 6 votes vote down vote up
function hideWin () {
  if (win) {
    if (isLinux()) {
      quit(app)
      return
    }
    win.hide()
    if (isMac && hideDockWhenWinClose) {
      app.dock.hide()
    }
  }
}
Example #13
Source File: background.js    From wl-admin with MIT License 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWindow();
});
Example #14
Source File: electron-main.js    From follow with GNU General Public License v3.0 6 votes vote down vote up
async function main() {
  try {
    await app.whenReady();
  } catch (e) {
    dialog.showErrorBox("Electron could not start", e.stack);
    app.exit(1);
  }

  try {
    // await setupAnalytics(ctx); // ctx.countlyDeviceId
    await setupI18n(ctx);
    await setupAppMenu(ctx);

    // await setupWebUI(ctx) // ctx.webui, launchWebUI
    await setupTray(ctx); // ctx.tray
    await setupDaemon(ctx); // ctx.getIpfsd, startIpfs, stopIpfs, restartIpfs
    // await setupAutoUpdater(ctx); // ctx.checkForUpdates

    await Promise.all([
      // setupArgvFilesHandler(ctx),
      setupAutoLaunch(ctx),
      setupAutoGc(ctx),
      setupPubsub(ctx),
      setupNamesysPubsub(ctx),
      // Setup global shortcuts
      setupDownloadCid(ctx),
      // setupIpfsOnPath(ctx)
    ]);

    // // Setup identity
    await setupIdentity(ctx);
    // open electron
    await createWindow(ctx);
    // // Setup pubsub
    // await setupOrbit(ctx);
  } catch (e) {
    handleError(e);
  }
}
Example #15
Source File: main.dev.js    From multistream with MIT License 6 votes vote down vote up
// /**
//  *
//  *
//  * @returns {Array}
//  * extensionss
//  */
// const installExtensions = async() => {
// 	const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

// 	return installer(REACT_DEVELOPER_TOOLS, forceDownload);
// };

/**
 * Add event listeners...
 */

app.on("window-all-closed", () => {
	// Respect the OSX convention of having the application in memory even
	// after all windows have been closed
	if (process.platform !== "darwin") {
		app.quit();
	}
});
Example #16
Source File: electron-main.js    From loa-details with GNU General Public License v3.0 6 votes vote down vote up
app.whenReady().then(() => {
  // Don't create prelauncher if debugging
  if (!process.env.DEBUGGING) {
    prelauncherWindow = createPrelauncherWindow();
    prelauncherWindow.on("show", () => {
      checkForUpdates();
    });
  } else {
    startApplication();
  }
});
Example #17
Source File: background.js    From linked with GNU General Public License v3.0 6 votes vote down vote up
reopenWindowAndSendWebContents = (message) => {
  if (!win) {
    createWindow()
    app.whenReady().then(() => {
      setTimeout(() => {
        win.webContents.send(message)
      }, 300)
    })
  }
  win.webContents.send(message)
}
Example #18
Source File: background.js    From vupc with MIT License 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWindow();
});
Example #19
Source File: AutoUpdater.js    From makerverse with GNU General Public License v3.0 6 votes vote down vote up
constructor(window) {
        if (process.platform !== 'darwin') {
            return;
        }

        autoUpdater.addListener('update-available', (event) => {
            log.debug('A new update is available');
        });
        // On Windows only `releaseName` is available.
        autoUpdater.addListener('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateURL) => {
            const title = 'A new update is ready to install';
            const message = `Version ${releaseName} is downloaded and will be automatically installed on quit`;
            notify(title, message);
        });
        autoUpdater.addListener('error', (err) => {
            log.error(err);
        });
        autoUpdater.addListener('checking-for-update', () => {
            log.debug('checking-for-update');
        });
        autoUpdater.addListener('update-not-available', () => {
            log.debug('update-not-available');
        });

        const updateServerHost = ''; // FIXME
        const platform = os.platform();
        const arch = os.arch();
        const version = app.getVersion();
        const feedURL = `https://${updateServerHost}/update/${platform}-${arch}/${version}`;
        autoUpdater.setFeedURL(feedURL);

        window.webContents.once('did-frame-finish-load', (event) => {
            autoUpdater.checkForUpdates();
        });
    }
Example #20
Source File: AlfwCommon.js    From ntfstool with MIT License 6 votes vote down vote up
/**
 * get the ntfstool version
 * @returns {*}
 */
export function getPackageVersion() {
    try {
        let curVersion = process.env.NODE_ENV === 'development' ? process.env.npm_package_version : require('electron').remote.app.getVersion();
        saveLog.log(curVersion, "curVersion");
        return curVersion;
    } catch (e) {
        saveLog.error(e, "getPackageVersion error");
        return "45.00";
    }
}
Example #21
Source File: background.js    From EveReader with GNU Affero General Public License v3.0 6 votes vote down vote up
app.on("second-instance", (event, argv, cwd) => {
  process.chdir(cwd);
  if (eveApp == null) {
    console.error("Error when trying to reach primary Eve-Reader instance");
    app.quit();
    return false;
  }
  eveApp.open(argv);
  return true;
});
Example #22
Source File: index.js    From brisque-2.0-desktop with MIT License 6 votes vote down vote up
app.on('ready', async () => {
  if (
    process.env.NODE_ENV === 'development' ||
    process.env.DEBUG_PROD === 'true'
  ) {
    await installExtensions();
  }

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  //new AppUpdater();

  return brisque.start();
});
Example #23
Source File: application.js    From razer-macos with GNU General Public License v2.0 5 votes vote down vote up
createWindow() {
    this.browserWindow = new BrowserWindow({
      webPreferences: { nodeIntegration: true },
      //titleBarStyle: 'hidden',
      height: 800, // This is adjusted later with window.setSize
      resizable: false,
      width: 500,
      minWidth: 320,
      minHeight: 320,
      y: 100,
      // Set the default background color of the window to match the CSS
      // background color of the page, this prevents any white flickering
      backgroundColor: '#202124',
      // Don't show the window until it's ready, this prevents any white flickering
      show: false,
    });
    if (this.isDevelopment) {
      this.browserWindow.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`);
      this.browserWindow.resizable = true;
    } else {
      this.browserWindow.loadFile(path.join(__dirname, 'index.html'));
    }

    // Handle window logic properly on macOS:
    // 1. App should not terminate if window has been closed
    // 2. Click on icon in dock should re-open the window
    // 3. ⌘+Q should close the window and quit the app
    this.browserWindow.on('close', (e) => {
      if (!this.forceQuit) {
        e.preventDefault();
        this.browserWindow.hide();
      }
    });

    this.app.on('activate', () => {
      this.browserWindow.show();
    });

    this.app.on('before-quit', () => {
      this.forceQuit = true;
    });

    if (this.isDevelopment) {
      // auto-open dev tools
      //this.browserWindow.webContents.openDevTools();

      // add inspect element on right click menu
      this.browserWindow.webContents.on('context-menu', (e, props) => {
        const that = this;
        Menu.buildFromTemplate([
          {
            label: 'Inspect element',
            click() {
              that.browserWindow.inspectElement(props.x, props.y);
            },
          },
        ]).popup(this.browserWindow);
      });
    }
  }
Example #24
Source File: electron-main.js    From quasar-manage with MIT License 5 votes vote down vote up
app.on('ready', createWindow)
Example #25
Source File: index.js    From NIM-Pools-Hub-Miner with GNU General Public License v3.0 5 votes vote down vote up
function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 560,
    width: process.env.NODE_ENV === "development" ? 1090 : 660,
    center: true,
    resizable: false,
    fullscreenable: false,
    frame: false,
    transparent: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      experimentalFeatures: true,
    },
  });
  if (process.env.NODE_ENV !== "development") mainWindow.removeMenu();

  log("Detecting UV_THREADPOOL_SIZE: " + process.env.UV_THREADPOOL_SIZE);

  if (!process.env.UV_THREADPOOL_SIZE) {
    process.env.UV_THREADPOOL_SIZE = 128;
    if (process.platform === "win32") {
      const Shell = require("node-powershell");
      let ps = new Shell({
        executionPolicy: "Bypass",
        noProfile: true,
      });
      const command =
        "[Environment]::SetEnvironmentVariable('UV_THREADPOOL_SIZE', 128, 'User')";
      ps.addCommand(command);
      ps.invoke()
        .then((output) => {
          dialog.showMessageBox({
            type: "info",
            message:
              "First time setup completed. NIM Pools Hub Miner will now restart.",
          });
          app.relaunch();
          app.quit();
        })
        .catch((err) => {
          console.log(err);
          ps.dispose();
        });
    }
  } else {
    log(`Detected ${process.env.UV_THREADPOOL_SIZE} threadpool size`);
  }

  log("Nimiq initialization");
  Nimiq.GenesisConfig.main();

  store.dispatch("setAppVersion", app.getVersion());
  store.dispatch("setCpuHashrate", null);
  store.dispatch("setGpuHashrate", null);
  store.dispatch("setMiningCPU", false);
  store.dispatch("setMiningGPU", false);

  mainWindow.loadURL(winURL);

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}
Example #26
Source File: background.js    From melvor-mod-manager with MIT License 5 votes vote down vote up
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
Example #27
Source File: ScratchDesktopTelemetry.js    From clipcc-desktop with GNU Affero General Public License v3.0 5 votes vote down vote up
APP_VERSION = app.getVersion()
Example #28
Source File: index.js    From FreeTube-Vue with GNU Affero General Public License v3.0 5 votes vote down vote up
localDataStorage = app.getPath('userData')
Example #29
Source File: main.js    From ioHookElectronWebpack with MIT License 5 votes vote down vote up
// IMPORTANT: option should be set to false to make it possible for ioHook global event
// tracker boundaries works correctly.
app.allowRendererProcessReuse = false;