electron#app TypeScript 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: utilities.ts    From Creators.TF-Community-Launcher with MIT License 7 votes vote down vote up
static GetNewLoadingPopup(title: string, mainWindow: any, onCanceled: () => void): any {
        const progressBar = new ProgressBar({
            text: title,
            detail: "...",
            browserWindow: {
                webPreferences: {
                    nodeIntegration: true
                },
                parent: mainWindow,
                modal: true,
                title: title,
                backgroundColor: "#2b2826",
                closable: true
            },
            style: {
                text: loadingTextStyle,
                detail: loadingTextStyle,
                value: loadingTextStyle
            }
        }, app);
        
        progressBar.on("aborted", onCanceled);

        return progressBar;
    }
Example #2
Source File: index.ts    From 3Speak-app with GNU General Public License v3.0 6 votes vote down vote up
async function startup(): Promise<void> {
  const updater = new AutoUpdater()
  void updater.run()

  try {
    new IpcAdapter(core).start()
    await core.start()
  } catch (ex) {
    console.error(ex)
    app.quit()
  }
}
Example #3
Source File: preferences.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
export function initializeDefaultPreferences() {
  const isBetaBuild = app.getVersion().toLowerCase().indexOf("beta") != -1;
  const defaultReleaseChannel = isBetaBuild ? WowUpReleaseChannelType.Beta : WowUpReleaseChannelType.Stable;

  setDefaultPreference(ENABLE_SYSTEM_NOTIFICATIONS_PREFERENCE_KEY, true);
  setDefaultPreference(COLLAPSE_TO_TRAY_PREFERENCE_KEY, true);
  setDefaultPreference(USE_HARDWARE_ACCELERATION_PREFERENCE_KEY, true);
  setDefaultPreference(CURRENT_THEME_KEY, DEFAULT_THEME);
  setDefaultPreference(WOWUP_RELEASE_CHANNEL_PREFERENCE_KEY, defaultReleaseChannel);
  setDefaultPreference(USE_SYMLINK_MODE_PREFERENCE_KEY, false);
  setDefaultPreference(ENABLE_APP_BADGE_KEY, true);
  setDefaultPreference(TRUSTED_DOMAINS_KEY, DEFAULT_TRUSTED_DOMAINS);
  setDefaultPreference(ACCT_PUSH_ENABLED_KEY, false);
}
Example #4
Source File: background.ts    From cashcash-desktop 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 () => {
    try {
        await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
        // tslint:disable-next-line:no-console
        console.error('Vue Devtools failed to install:', e.toString());
    }
    createWindow();
});
Example #5
Source File: main.dev.ts    From Oratio with MIT License 6 votes vote down vote up
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();
  }
  globalShortcut.unregisterAll();
  server.close();
});
Example #6
Source File: rewind.events.ts    From rewind with MIT License 6 votes vote down vote up
export function setupEventListeners(rewindElectronApp: RewindElectronApp) {
  // BackendAPI
  ipcMain.handle("getPath", (event, type) => backendPreloadAPI.getPath(type));

  // Others

  // Does not work
  // for (const [key, handler] of Object.entries(frontendPreloadAPI)) {
  //   ipcMain.handle(key, (event, args) => handler(...args));
  // }
  const app = rewindElectronApp.application;

  ipcMain.handle("selectDirectory", (event, defaultPath) => userSelectDirectory(defaultPath));
  ipcMain.handle("selectFile", (event, defaultPath) => userSelectFile(defaultPath));
  ipcMain.handle("getPlatform", () => process.platform);
  ipcMain.handle("getAppVersion", () => app.getVersion());
  ipcMain.handle("reboot", () => {
    app.relaunch();
    app.quit();
  });
}
Example #7
Source File: test-electron.ts    From FIDO2Client with MIT License 6 votes vote down vote up
app.whenReady().then(() => {

    let win = new BrowserWindow({
        webPreferences: {
            nodeIntegration: false,
            enableRemoteModule: false,
            contextIsolation: false,
            preload: PreloadPath,
        },
    });

    win.loadURL('https://webauthn.cybersecvn.com').then(() => {
        // win.webContents.openDevTools();
        win.maximize();
    });

    let fido2 = new FIDO2Client();
    ipcMain.handle('navigator.credentials.create', (event, options) => fido2.makeCredential(event.sender.getURL(), options));
    ipcMain.handle('navigator.credentials.get', (event, options) => fido2.getAssertion(event.sender.getURL(), options));
});
Example #8
Source File: main.ts    From rewind with MIT License 6 votes vote down vote up
// TODO: Squirrel events

(function main() {
  console.log(`AppDataPath=${app.getPath("appData")}`);
  const userDataPath = app.getPath("userData");
  const settings = readRewindElectronSettings(userDataPath);
  const isDev = isDevelopmentMode();
  console.log("Starting MainWindow with settings ", JSON.stringify(settings), isDev);
  const rewindElectronApp = new RewindElectronApp(app, settings, isDev);
  rewindElectronApp.boot();
  setupEventListeners(rewindElectronApp);
})();
Example #9
Source File: main.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
app.on('ready', async () => {
  logger.info('App is running', {
    source: 'init',
    version: app.getVersion(),
    osName: os.type(),
    osRelease: os.release(),
    logLevel: logger.level
  })

  createFileProtocol()

  setupConfigEvents()
  createTray()
  setupShowHide()
  loadAndCacheGameCfg()

  setTimeout(
    async () => {
      await createOverlayWindow()
      setupShortcuts()
      setupAltVisibility()
      LogWatcher.start()
    },
    // fixes(linux): window is black instead of transparent
    process.platform === 'linux' ? 1000 : 0
  )

  if (process.env.NODE_ENV === 'production') {
    checkForUpdates()
  }
})
Example #10
Source File: main.ts    From animation-editor with MIT License 6 votes vote down vote up
app.on("ready", () => {
	Menu.setApplicationMenu(electronMenu);

	session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
		callback({
			responseHeaders: {
				...details.responseHeaders,
				// DevTools don't work when unsafe-eval is present. Commenting this out until I figure out
				// how to add a CSP without breaking DevTools or something else.
				//
				// "Content-Security-Policy": [
				// 	"default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self';",
				// ],

				// See https://developer.chrome.com/blog/enabling-shared-array-buffer/
				"Cross-Origin-Embedder-Policy": "require-corp",
				"Cross-Origin-Opener-Policy": "same-origin",
			},
		});
	});

	createElectronWindow();
});
Example #11
Source File: logger.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
logger = winston.createLogger({
  level: config.get('logLevel'),
  format: winston.format.json(),
  defaultMeta: { source: 'etc' },
  transports: [
    new winston.transports.File({
      filename: path.join(app.getPath('userData'), 'apt-data', 'logs.txt'),
      options: { flags: 'w' },
      format: winston.format.printf((info) => {
        const { source, level, message, ...meta } = info
        return `${level} [${source}]: ${message} ${JSON.stringify(meta)}`
      })
    })
  ]
})
Example #12
Source File: main.ts    From DittoPlusPlus with MIT License 6 votes vote down vote up
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  unRegisterKeyboardShortcuts();
  if (process.platform !== 'darwin') {
    isQuitting = true;
    app.quit();
  }
});
Example #13
Source File: index.ts    From image-optimizer with MIT License 6 votes vote down vote up
function createWindow () {
  const bounds = store.app.get('bounds')
  mainWindow = new BrowserWindow({
    width: 550,
    height: 370,
    ...bounds,
    titleBarStyle: 'hidden',
    resizable: false,
    backgroundColor: '#212123',
    webPreferences: {
      preload: path.resolve(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: true
    }
  })

  if (isDev) {
    const rendererPort = process.argv[2]
    mainWindow.loadURL(`http://localhost:${rendererPort}`)
    mainWindow.webContents.openDevTools({ mode: 'detach' })
  } else {
    mainWindow.loadFile(path.resolve(app.getAppPath(), 'src/renderer/index.html'))
  }

  mainWindow.on('close', () => {
    store.app.set('bounds', mainWindow.getBounds())
  })

  return { mainWindow }
}
Example #14
Source File: background.ts    From IYUU-GUI with GNU Affero General Public License v3.0 6 votes vote down vote up
function initTray() {
  tray = new Tray(path.join(__static, 'assets/iyuu.png'))
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '退出', click: () => {
        app.quit()
      }
    }
  ])

  tray.on('click', () => {
    win && win.show();
  })

  // Call this again for Linux because we modified the context menu
  tray.setContextMenu(contextMenu)
}
Example #15
Source File: main.ts    From simulator with Apache License 2.0 6 votes vote down vote up
/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
Example #16
Source File: main.dev.ts    From ow-mod-manager with MIT License 6 votes vote down vote up
createWindow = async () => {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 850,
    minWidth: 750,
    minHeight: 400,
    webPreferences: {
      nodeIntegration: !isProduction,
      enableRemoteModule: true,
      preload: isProduction
        ? path.join(__dirname, 'dist/renderer.prod.js')
        : undefined,
    },
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  if (isProduction) {
    mainWindow.setMenu(null);
  }

  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    mainWindow.setTitle(`Outer Wilds Mod Manager ${app.getVersion()}`);
  });

  setUpProtocolMessage(process.argv);

  checkForUpdates();
}
Example #17
Source File: background.ts    From project_nodeSnap with GNU General Public License v3.0 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) {
        /**
         * Since this is Vue 3, we need to download the beta extention.
         * You can download it on your browser (chromuim based) and set the path here
         */
        /*await session.defaultSession.loadExtension(
      "C:/Users/Moncef/AppData/Local/BraveSoftware/Brave-Browser/User Data/Default/Extensions/ljjemllljcmogpfapbkkighbhhppjdbg/6.0.0.3_0"
    );*/
    }
    //myLogger.log("creating main window...");
    createWindow();
});
Example #18
Source File: main.ts    From simulator with Apache License 2.0 6 votes vote down vote up
app
  .whenReady()
  .then(() => {
    createWindow();
    app.on('activate', () => {
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);
Example #19
Source File: main.dev.ts    From amazon-chime-sdk-classroom-demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #20
Source File: shell.ts    From ngx-electronify with MIT License 6 votes vote down vote up
app.on('web-contents-created', (_, contents) => {
  // Angular router is ignored on `will-navigate` event
  contents.on('will-navigate', (event, url) => {
    // allow hot reload to work properly
    if (url !== appUrl) {
      event.preventDefault();
    }
  });

  contents.setWindowOpenHandler(({ url }) => {
    // open all blank href links using the OS default browser
    setImmediate(() => {
      shell.openExternal(url);
    });
    return { action: 'deny' };
  });
});
Example #21
Source File: app.ts    From noteworthy with GNU Affero General Public License v3.0 6 votes vote down vote up
// == Quitting ====================================== //

	/**
	 * Perform all steps needed to shut down the application.
	 * @caution Actually shuts down!  Doesn't ask about unsaved changes!)
	 */
	quit(){
		// announce globally that we're actually quitting!
		global.isQuitting = true;
		// clean up
		/** @todo (9/13/20) these are global services, 
		 *    is it actually appropriate to destroy them here?
		 */
		this.detach__beforeQuit();
		this._workspaceService.closeWorkspace()
		this._fsal.close();
		app.quit();
	}
Example #22
Source File: main.ts    From SpaceEye with MIT License 6 votes vote down vote up
/**
 * Configure whether the app should start on login.
 *
 * @param shouldStart - Whether the app should start on login
 */
async function configureStartOnLogin(shouldStart: boolean) {
    // Handle differently if windows store build
    if (process.windowsStore === true) {
        let task
        try {
            task = await WindowsStoreAutoLaunch.getStartupTask('SpaceEyeStartup')
        } catch (error) {
            log.error('Failed to get start on login MS task:', error)
            return
        }
        if (task !== undefined && task.state !== StartupTaskState.disabledByUser) {
            if (task.state === StartupTaskState.disabled && shouldStart) {
                task.requestEnableAsync((error, _) => {
                    if (error) {
                        log.error('Failed to enable start on login for MS build')
                    }
                })
            } else if (task.state === StartupTaskState.enabled && !shouldStart) {
                task.disable()
            }
        } else {
            log.warn('User has disabled start on login from task manager; unable to change')
        }
        return
    }
    const loginItemSettings = app.getLoginItemSettings()

    // If not set to what it should be, update it
    if (loginItemSettings.openAtLogin !== shouldStart) {
        app.setLoginItemSettings({ openAtLogin: shouldStart })
    }
}
Example #23
Source File: main.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
app.on('ready', () => {
  // Load settings from file before the window is created
  getSettingsHandler.initSettings().then(() => {
    createBridgeWindow()
    if (!isDevBuild) {
      updateChecker.checkForUpdates()
    }
  })
})
Example #24
Source File: main.dev.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
app.on('ready', async () => {
  // does not work in development and MacOS requires the application to be signed
  if (process.env.NODE_ENV !== 'development' && !isMacOS) {
    try {
      await autoUpdater.checkForUpdates();
    } catch (error) {
      logger.error(error);
    }
  }
});
Example #25
Source File: window.ts    From noteworthy with GNU Affero General Public License v3.0 6 votes vote down vote up
makeWindow(id=this.name, options=this.options, stateOptions=this.stateOptions) {
		stateOptions = _.merge({
			file: `${id}.json`,
			defaultWidth: 600,
			defaultHeight: 600
		}, stateOptions);

		const state = windowStateKeeper(stateOptions),
			dimensions = _.pick(state, ['x', 'y', 'width', 'height']);

		/** @todo get rid of lodash */
		options = _.merge(dimensions, {
			frame: true, //!is.macos,
			show: false,
			title: "Noteworthy",
			//titleBarStyle: 'hiddenInset',
			webPreferences: {
				webSecurity: true,
				sandbox: true,
				contextIsolation: true,
				preload: path.join(app.getAppPath(), 'dist/preload/preload.js'),
			},
			icon: "assets/icon/noteworthy-icon-512.png"
		}, options);

		const win = new BrowserWindow(options);
		state.manage(win);

		return win;
	}
Example #26
Source File: index.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
startFileLogging = (): void => {
  // use a fixed path, to ensure log shows outside Electron dist
  const logPath = `${pathRoot}/debug-${app.isPackaged ? 'prod' : 'dev' }.log`
  const logFile = fs.createWriteStream(logPath, { flags: 'w' })
  const logStdout = process.stdout

  console.log = function(...args) {
    // @ts-ignore
    logFile.write(util.format.apply(null, args) + '\n')
    // @ts-ignore
    logStdout.write(util.format.apply(null, args) + '\n')
  }
  console.debug = console.log
  console.error = console.log

  console.log('logger running')
}
Example #27
Source File: main.dev.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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') {
    localServer.stop();
    app.quit();
  }
});
Example #28
Source File: index.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
createWindow = (): void => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1080,
    height: 900,
    icon: path.join(__dirname, 'assets/icon.png'), // Linux app icon
    webPreferences: {
      nodeIntegration: true,
      // May want to use app.getAppPath() instead
      // preload: path.join(__dirname, 'preload.js'), // use a preload script
      // preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      // allowRunningInsecureContent: true,
      // webSecurity: false,
      // sandbox: false,
    }
  });

  // and load the index.html of the app.
  // mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
  mainWindow.loadURL(`http://localhost:${uiPort}`)

  // Open the DevTools for `npm run start`
  if (!app.isPackaged) mainWindow.webContents.openDevTools()

  mainWindow.on('close', function () {
    console.debug('close')
    clearLocalStorage()
  })
  mainWindow.on('closed', function () {
    console.debug('closed')
    mainWindow = null
  })

  // Open links in browser instead of new electron window
  mainWindow.webContents.on('new-window', function(e: NewWindowWebContentsEvent, url: string) {
    e.preventDefault()
    shell.openExternal(url)
  })
}
Example #29
Source File: main.ts    From dbm with Apache License 2.0 6 votes vote down vote up
function createWindow(): BrowserWindow {
  win = new BrowserWindow({
    center: true,
    width: 800,
    height: 550,
    webPreferences: {
      nodeIntegration: true,
      allowRunningInsecureContent: isDevelopment,
      contextIsolation: false,
      enableRemoteModule: false,
      // Fix Access-Control-Allow-Origin
      webSecurity: false
    }
  });
  createMenu(app);
  createAbout(app);
  // Maximize window
  win.maximize();
  const winURL = isDevelopment
    ? 'http://localhost:4200'
    : `file://${path.join(__dirname, '/../renderer/index.html')}`;
  if (isDevelopment) {
    win.webContents.openDevTools();
  }
  win.loadURL(winURL).then(() => {
  });
  win.on('closed', (event) => {
    win = null;
    event.preventDefault();
  });
  if (isDevelopment) {
    app.dock.setIcon(path.join(__dirname, '../shared/assets/icons/favicon.png'));
  }
  handlerUpdater(win);
  return win;
}