Giter VIP home page Giter VIP logo

electron-util's Introduction

electron-util Build Status

Useful utilities for developing Electron apps and modules

You can use this module directly in both the main and renderer process.

Install

$ npm install electron-util

Requires Electron 4 or later.

Usage

const {is} = require('electron-util');

console.log(is.macos && is.main);
//=> true

API

Contents

api

Type: Object

Access the Electron APIs in both the main and renderer process without having to care about which one you're in.

For example, in the renderer process:

api.app.quit();

The app API is usually only available in the main process.

is

Type: Object

Check for various things:

  • macos - Running on macOS
  • linux - Running on Linux
  • windows - Running on Windows
  • main - Running on the main process
  • renderer - Running on the renderer process
  • development - Running in development, not in production
  • usingAsar - The app is using ASAR
  • macAppStore - The app is an Mac App Store build
  • windowsStore - The app is a Windows Store AppX build

electronVersion

Type: string
Example: 1.7.9

Electron version.

chromeVersion

Type: string
Example: 62.0.3202

Chrome version in Electron.

platform(choices)

Type: Function

Accepts an object with the keys as either macos, windows, linux, or default, and picks the appropriate key depending on the current platform. If no platform key is matched, the default key is used if it exists. If the value is a function, it will be executed, and the returned value will be used.

init({
	enableUnicorn: util.platform({
		macos: true,
		windows: false,
		linux: () => false
	})
});

activeWindow()

Type: Function

Returns the active window.

runJS(code, [window])

Type: Function

Run some JavaScript in the active or given window.

Returns a promise for the result of the executed code or a rejected promise if the result is a rejected promise.

fixPathForAsarUnpack(path)

Type: Function

ASAR is great, but it has limitations when it comes to executing binaries. For example, child_process.spawn() is not automatically handled. So you would have to unpack the binary, for example, with the asarUnpack option in electron-builder. This creates a problem as the path to the binary changes, but your path.join(__dirname, 'binary') is not changed. To make it work you need to fix the path. That's the purpose of this method.

Before:

/Users/sindresorhus/Kap.app/Contents/Resources/app.asar/node_modules/foo/binary

After:

/Users/sindresorhus/Kap.app/Contents/Resources/app.asar.unpack/node_modules/foo/binary

enforceMacOSAppLocation() macOS

Type: Function

On macOS, for security reasons, if an app is launched outside the Applications folder, it will run in a read-only disk image, which could cause subtle problems for your app. Use this method to ensure the app lives in the Applications folder.

It must not be used until the app.on('ready') event has been emitted.

It will be a no-op during development and on other systems than macOS.

It will offer to automatically move the app for the user:

menuBarHeight() macOS

Returns the height of the menu bar on macOS, or 0 if not macOS.

getWindowBoundsCentered([options])

Get the bounds of a window as if it was centered on the screen.

options

Type: Object

window

Type: BrowserWindow
Default: Current window

The window to get the bounds of.

size

Type: Object
Default: Size of window

Set a new window size. Example: {width: 600, height: 400}

setWindowBounds(bounds, [options])

Set the bounds of a window. This is similar to the BrowserWindow#setBounds() method, but it allows setting any of the x, y, width, height properties, instead of forcing you to set them all at once. The properties that are not set will just fall back to the current ones.

options

Type: Object

window

Type: BrowserWindow
Default: Current window

The window to set the bounds of.

animated

Type: boolean
Default: false

Animate the change.

centerWindow([options])

Center a window on the screen.

options

Type: Object

window

Type: BrowserWindow
Default: Current window

The window to center.

size

Type: Object
Default: Size of window

Set a new window size. Example: {width: 600, height: 400}

animated

Type: boolean
Default: false

Animate the change.

disableZoom([window])

Disable zooming, usually caused by pinching the trackpad on macOS or Ctrl+ on Windows.

window

Type: BrowserWindow
Default: Current window

appLaunchTimestamp

Type: number

A timestamp (Date.now()) of when your app launched.

isFirstAppLaunch()

Returns a boolean of whether it's the first time your app is launched.

It works by writing a file to app.getPath('userData') if it doesn't exist and checks that. That means it will return true the first time you add this check to your app.

darkMode

Type: Object

const {darkMode} = require('electron-util');

console.log(darkMode.isEnabled);
//=> false

darkMode.onChange(() => {
	console.log(darkMode.isEnabled);
	//=> true
});

isEnabled

Type: boolean

Whether the macOS dark mode is enabled.

On Windows and Linux, it's false.

onChange(callback)

The callback function is called when the macOS dark mode is toggled.

Returns a function, that when called, unsubscribes the listener.

Calling it on Window and Linux works, but it just returns a no-op function.

setContentSecurityPolicy(policy, [options])

Set a Content Security Policy for your app.

Don't forget to validate the policy after changes.

const {setContentSecurityPolicy} = require('electron-util');

setContentSecurityPolicy(`
	default-src 'none';
	script-src 'self';
	img-src 'self' data:;
	style-src 'self';
	font-src 'self';
	connect-src 'self' https://api.example.com;
	base-uri 'none';
	form-action 'none';
	frame-ancestors 'none';
`);

policy

Type: string

You can put rules on separate lines, but lines must end in a semicolon.

options

Type: Object

session

Type: Session
Default: electron.session.defaultSession

The session to apply the policy to.

openNewGitHubIssue(options)

Opens the new issue view on the given GitHub repo in the browser. Optionally, with some fields like title and body prefilled. The options are passed to the new-github-issue-url package.

const {openNewGitHubIssue} = require('electron-util');

openNewGitHubIssue({
	user: 'sindresorhus',
	repo: 'playground',
	body: 'Hello'
});

openUrlMenuItem(options)

Accepts the same options as new MenuItem() in addition to a url option.

If you specify the click option, its handler will be called before the URL is opened.

Returns a MenuItemConstructorOptions that creates a menu item, which opens the given URL in the browser when clicked.

const {Menu} = require('electron');
const {openUrlMenuItem} = require('electron-util');

const menu = Menu.buildFromTemplate([
	{
		label: 'Help',
		submenu: [
			openUrlMenuItem({
				label: 'Website',
				url: 'https://sindresorhus.com'
			})
		]
	}
]);

Menu.setApplicationMenu(menu);

showAboutWindow(options)

Shows an 'About' window. On macOS, the native 'About' window is shown, and on Linux and Windows, a simple custom dialog is shown.

On macOS, the icon, text, and title options are ignored.

It will show Electron as the app name until you build your app for production.

The about window on Ubuntu

const {showAboutWindow} = require('electron-util');

showAboutWindow({
	icon: path.join(__dirname, 'static/Icon.png'),
	copyright: 'Copyright © Sindre Sorhus',
	text: 'Some more info.'
});

options

Type: Object

icon

Type: string

An absolute path to the app icon.

copyright

Type: string

The copyright text.

text

Type: string

Some additional text if needed.

title

Type: string
Default: About

Customizable for localization. Used in the menu item label and window title.

The app name is automatically appended at runtime.

aboutMenuItem(options) Linux Windows

Accepts the same options as .showAboutWindow().

Returns a MenuItemConstructorOptions that creates a menu item, which shows the about dialog when clicked.

const {Menu} = require('electron');
const {aboutMenuItem} = require('electron-util');

const menu = Menu.buildFromTemplate([
	{
		label: 'Help',
		submenu: [
			aboutMenuItem({
				icon: path.join(__dirname, 'static/Icon.png'),
				copyright: 'Copyright © Sindre Sorhus',
				text: 'Some more info.'
			})
		]
	}
]);

Menu.setApplicationMenu(menu);

debugInfo()

Returns a string with debug info suitable for inclusion in bug reports.

For example, use this in the body option of the .openNewGitHubIssue() method.

const {debugInfo} = require('electron-util');

console.log(debugInfo());
/*
AppName 2.21.0
Electron 3.0.6
darwin 18.2.0
Locale: en-US
*/

appMenu([menuItems]) macOS

Creating the app menu (the first menu) on macOS requires a lot of boilerplate. This method includes the default boilerplate and lets you add additional menu items in the correct place.

menuItems

Type: MenuItem[]

Menu items to add below the About App Name menu item.

Usually, you would add at least a Preferences… menu item:

const {Menu} = require('electron');
const {appMenu} = require('electron-util');

const menu = Menu.buildFromTemplate([
	appMenu([
		{
			label: 'Preferences…',
			accelerator: 'Command+,',
			click() {}
		}
	])
]);

Menu.setApplicationMenu(menu);

Node.js API

This is for non-Electron code that might be included in an Electron app. For example, if you want to add special support for Electron in a vanilla Node.js module.

const electronUtil = require('electron-util/node');

if (electronUtil.isElectron) {
	// Electron workaround
} else {
	// Normal code
}

isElectron

Type: boolean

Check if you're running in an Electron app.

electronVersion

Type: string
Example: 1.7.9

Electron version. Returns 0.0.0 when not in an Electron app.

isUsingAsar

Type: boolean

Check if the Electron app you're running in is using ASAR.

fixPathForAsarUnpack(path)

Same as the above Electron version.

Related

License

MIT © Sindre Sorhus

electron-util's People

Contributors

sindresorhus avatar cvx avatar albinekb avatar qazbnm456 avatar mansarde avatar jake avatar joecohens avatar marshallofsound avatar acheronfail avatar

Watchers

Zhao Lei avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.