밑의 예시는 마지막 윈도우가 종료되었을 때, 어플리케이션을 종료시키는 예시입니다:
```javascript
-const { app } = require('electron');
+const {app} = require('electron');
app.on('window-all-closed', () => {
app.quit();
});
기본 동작을 방지하고 인증을 승인할 수 있습니다.
```javascript
-app.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
- if (url == "https://github.com") {
- // Verification logic.
+app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
+ if (url === 'https://github.com') {
+ // 확인 로직.
event.preventDefault();
callback(true);
} else {
것을 막습니다.
```javascript
-app.on('select-client-certificate', function(event, webContents, url, list, callback) {
+app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault();
callback(list[0]);
-})
+});
```
### Event: 'login'
app.on('login', (event, webContents, request, authInfo, callback) => {
event.preventDefault();
callback('username', 'secret');
-})
+});
```
### Event: 'gpu-process-crashed'
```javascript
// 메인 프로세스에서
-const { BrowserWindow } = require('electron');
+const {BrowserWindow} = require('electron');
// 또는 렌더러 프로세스에서
-const { BrowserWindow } = require('electron').remote;
+const {BrowserWindow} = require('electron').remote;
-let win = new BrowserWindow({ width: 800, height: 600, show: false });
+let win = new BrowserWindow({width: 800, height: 600, show: false});
win.on('closed', () => {
win = null;
});
예시는 다음과 같습니다:
```javascript
-window.onbeforeunload = function(e) {
+window.onbeforeunload = (e) => {
console.log('I do not want to be closed');
// 반드시 문자열을 반환해야 하고 사용자에게 페이지 언로드에 대한 확인 창을 보여주는
```javascript
// `win`은 BrowserWindow의 인스턴스입니다
-var win = new BrowserWindow({ width: 800, height: 600 });
+let win = new BrowserWindow({width: 800, height: 600});
```
### `win.webContents`
표시하기 위해 사용할 것입니다:
```javascript
-var toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
+let toolbarRect = document.getElementById('toolbar').getBoundingClientRect();
win.setSheetOffset(toolbarRect.height);
```
명령줄 옵션을 추가로 지정할 수 있습니다:
```javascript
-const { app } = require('electron');
+const {app} = require('electron');
app.commandLine.appendSwitch('remote-debugging-port', '8315');
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');
## --ssl-version-fallback-min=`version`
-TLS fallback에서 사용할 SSL/TLS 최소 버전을 지정합니다. ("tls1", "tls1.1",
-"tls1.2")
+TLS fallback에서 사용할 SSL/TLS 최소 버전을 지정합니다. (`tls1`, `tls1.1`, `tls1.2`)
## --cipher-suite-blacklist=`cipher_suites`
다음 예시는 클립보드에 문자열을 쓰는 방법을 보여줍니다:
```javascript
-const { clipboard } = require('electron');
+const {clipboard} = require('electron');
clipboard.writeText('Example String');
```
* `type` String (optional)
```javascript
-clipboard.write({text: 'test', html: "<b>test</b>"});
+clipboard.write({text: 'test', html: '<b>test</b>'});
```
`data`를 클립보드에 씁니다.
`chrome://tracing/` 페이지를 열고 생성된 파일을 로드하면 결과를 볼 수 있습니다.
```javascript
-const { contentTracing } = require('electron');
+const {contentTracing} = require('electron');
const options = {
categoryFilter: '*',
traceOptions: 'record-until-full,enable-sampling'
};
-contentTracing.startRecording(options, function() {
+contentTracing.startRecording(options, () => {
console.log('Tracing started');
setTimeout(() => {
다음 예시는 윈격 서버에 어플리케이션 크래시 정보를 자동으로 보고하는 예시입니다:
```javascript
-const { crashReporter } = require('electron');
+const {crashReporter} = require('electron');
crashReporter.start({
productName: 'YourName',
```javascript
// 렌더러 프로세스 내부
-const { desktopCapturer } = require('electron');
+const {desktopCapturer} = require('electron');
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error;
- for (var i = 0; i < sources.length; ++i) {
- if (sources[i].name == "Electron") {
+ for (let i = 0; i < sources.length; ++i) {
+ if (sources[i].name === 'Electron') {
navigator.webkitGetUserMedia({
audio: false,
video: {
다음 예시는 파일과 디렉터리를 다중으로 선택하는 대화 상자를 표시하는 예시입니다:
```javascript
-var win = ...; // 대화 상자를 사용할 BrowserWindow 객체
-const { dialog } = require('electron');
-console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
+let win = ...; // 대화 상자를 사용할 BrowserWindow 객체
+const {dialog} = require('electron');
+console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}));
```
대화 상자는 Electron의 메인 스레드에서 열립니다. 만약 렌더러 프로세스에서 대화 상자
객체를 사용하고 싶다면, `remote`를 통해 접근하는 방법을 고려해야 합니다:
```javascript
-const { dialog } = require('electron').remote;
+const {dialog} = require('electron').remote;
```
## Methods
```javascript
{
filters: [
- { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
- { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
- { name: 'Custom File Type', extensions: ['as'] },
- { name: 'All Files', extensions: ['*'] }
+ {name: 'Images', extensions: ['jpg', 'png', 'gif']},
+ {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']},
+ {name: 'Custom File Type', extensions: ['as']},
+ {name: 'All Files', extensions: ['*']}
]
}
```
라벨을 가지고 있을 때 해당 버튼의 인덱스를 반환합니다. 따로 두 라벨이 지정되지
않은 경우 0을 반환합니다. OS X와 Windows에선 `cancelId` 지정 여부에 상관없이
"Cancel" 버튼이 언제나 `cancelId`로 지정됩니다.
- * `noLink` Boolean - Windows Electron은 "Cancel"이나 "Yes"와 같은 흔히 사용되는
- 버튼을 찾으려고 시도하고 대화 상자 내에서 해당 버튼을 커맨드 링크처럼 만듭니다.
- 이 기능으로 앱을 좀 더 Modern Windows 앱처럼 만들 수 있습니다. 이 기능을 원하지
- 않으면 `noLink`를 true로 지정하면 됩니다.
+ * `noLink` Boolean - Windows에서 Electron은 ("Cancel"이나 "Yes"와 같은) 흔히
+ 사용되는 버튼을 찾으려고 시도하고 대화 상자 내에서 해당 버튼을 커맨드 링크처럼
+ 만듭니다. 이 기능으로 앱을 좀 더 현대적인 Windows 앱처럼 만들 수 있습니다. 이
+ 기능을 원하지 않으면 `noLink`를 true로 지정하면 됩니다.
* `callback` Function (optional)
대화 상자를 표시합니다. `browserWindow`를 지정하면 대화 상자가 완전히 닫힐 때까지
console.log('Received bytes: ' + item.getReceivedBytes());
});
item.on('done', (e, state) => {
- if (state === "completed") {
- console.log("Download successfully");
+ if (state === 'completed') {
+ console.log('Download successfully');
} else {
- console.log("Download is cancelled or interrupted that can't be resumed");
+ console.log('Download is cancelled or interrupted that can\'t be resumed');
}
});
});
`options` 객체에서 `frame` 옵션을 `false`로 지정하면 됩니다:
```javascript
-const { BrowserWindow } = require('electron');
-let win = new BrowserWindow({ width: 800, height: 600, frame: false });
+const {BrowserWindow} = require('electron');
+let win = new BrowserWindow({width: 800, height: 600, frame: false});
```
### 최신 OS X에서 사용할 수 있는 대안
OS X 10.10 Yosemite 이후의 최신 버전부터는 테두리가 없는 창을 만들 때 새로운 방법을
사용할 수 있습니다. `frame` 옵션을 `false`로 지정하여 제목과 창 구성 요소를 모두
비활성화하는 대신 새로운 `titleBarStyle` 옵션을 통해 제목만 숨기고 창 구성 요소
-("흔히 신호등으로 알고 있는")의 기능과 창 크기를 그대로 유지할 수 있습니다:
+("신호등 버튼")의 기능과 창 크기를 그대로 유지할 수 있습니다:
```javascript
-let win = new BrowserWindow({ 'titleBarStyle': 'hidden' });
+let win = new BrowserWindow({titleBarStyle: 'hidden'});
```
## 투명한 창 만들기
바꿔주기만 하면됩니다:
```javascript
-let win = new BrowserWindow({ transparent: true, frame: false });
+let win = new BrowserWindow({transparent: true, frame: false});
```
### API의 한계
사용할 수 없습니다.
```javascript
-const electron = require('electron');
-const { app, globalShortcut } = electron;
+const {app, globalShortcut} = require('electron');
app.on('ready', () => {
// 'CommandOrControl+X' 단축키를 리스너에 등록합니다.
```javascript
// 메인 프로세스
-const { ipcMain } = require('electron');
+const {ipcMain} = require('electron');
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg); // "ping" 출력
event.sender.send('asynchronous-reply', 'pong');
```javascript
// 렌더러 프로세스 (웹 페이지)
-const { ipcRenderer } = require('electron');
+const {ipcRenderer} = require('electron');
console.log(ipc.sendSync('synchronous-message', 'ping')); // "pong" 출력
ipcRenderer.on('asynchronous-reply', (arg) => {
```html
<!-- index.html -->
<script>
-const { Menu, MenuItem } = require('electron').remote;
+const {Menu, MenuItem} = require('electron').remote;
const menu = new Menu();
-menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } }));
-menu.append(new MenuItem({ type: 'separator' }));
-menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true }));
+menu.append(new MenuItem({label: 'MenuItem1', click() { console.log('item 1 clicked'); }}));
+menu.append(new MenuItem({type: 'separator'}));
+menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}));
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
{
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
- click: (item, focusedWindow) => {
+ click(item, focusedWindow) {
if (focusedWindow) focusedWindow.reload();
}
},
{
label: 'Toggle Full Screen',
- accelerator: (() => {
- if (process.platform === 'darwin')
- return 'Ctrl+Command+F';
- else
- return 'F11';
- })(),
- click: (item, focusedWindow) => {
+ accelerator: process.platform === 'darwin' ? 'Ctrl+Command+F' : 'F11',
+ click(item, focusedWindow) {
if (focusedWindow)
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
}
},
{
label: 'Toggle Developer Tools',
- accelerator: (() => {
- if (process.platform == 'darwin')
- return 'Alt+Command+I';
- else
- return 'Ctrl+Shift+I';
- })(),
- click: (item, focusedWindow) => {
+ accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
+ click(item, focusedWindow) {
if (focusedWindow)
focusedWindow.webContents.toggleDevTools();
}
submenu: [
{
label: 'Learn More',
- click: () => { require('electron').shell.openExternal('http://electron.atom.io') }
+ click() { require('electron').shell.openExternal('http://electron.atom.io'); }
},
]
},
{
label: 'Quit',
accelerator: 'Command+Q',
- click: () => { app.quit(); }
+ click() { app.quit(); }
},
]
});
```javascript
const appIcon = new Tray('/Users/somebody/images/icon.png');
-let window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
+let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
```
이 예시는 클립보드로부터 가져온 `nativeImage`로 트레이 메뉴를 생성합니다:
```javascript
-var appIcon = new Tray('/Users/somebody/images/icon.png');
+let appIcon = new Tray('/Users/somebody/images/icon.png');
```
지원하는 DPI 접미사는 다음과 같습니다:
```javascript
const nativeImage = require('electron').nativeImage;
-
-var image = nativeImage.createFromPath('/Users/somebody/images/icon.png');
+let image = nativeImage.createFromPath('/Users/somebody/images/icon.png');
```
### `image.toPng()`
예시:
```javascript
-var app = require('app');
+const {app} = require('electron');
app.on('ready', () => {
require('electron').powerMonitor.on('suspend', () => {
예시:
```javascript
-const { powerSaveBlocker } = require('electron');
+const {powerSaveBlocker} = require('electron');
const id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));
// preload.js
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
-process.once('loaded', function() {
+process.once('loaded', () => {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;
});
다음 예시는 `file://` 프로토콜과 비슷한 일을 하는 커스텀 프로토콜을 설정합니다:
```javascript
-const {app, protocol} = require('electron')
-const path = require('path')
+const {app, protocol} = require('electron');
+const path = require('path');
-app.on('ready', function () {
+app.on('ready', () => {
protocol.registerFileProtocol('atom', function (request, callback) {
- const url = request.url.substr(7)
- callback({path: path.normalize(__dirname + '/' + url)})
+ const url = request.url.substr(7);
+ callback({path: path.normalize(__dirname + '/' + url)});
}, function (error) {
if (error)
- console.error('Failed to register protocol')
- })
-})
+ console.error('Failed to register protocol');
+ });
+});
```
**참고:** 모든 메서드는 따로 표기하지 않는 한 `app` 모듈의 `ready` 이벤트가 발생한
등록해야만 합니다:
```javascript
-protocol.registerStandardSchemes(['atom'])
-app.on('ready', function () {
- protocol.registerHttpProtocol('atom', ...)
-})
+protocol.registerStandardSchemes(['atom']);
+app.on('ready', () => {
+ protocol.registerHttpProtocol('atom', ...);
+});
```
**참고:** 이 메서드는 `app` 모듈의 `ready` 이벤트가 발생하기 이전에만 사용할 수
callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')});
}, (error) => {
if (error)
- console.error('Failed to register protocol')
+ console.error('Failed to register protocol');
});
```
다음 예시는 렌더러 프로세스에서 브라우저 창을 만드는 예시입니다:
```javascript
-const { BrowserWindow } = require('electron').remote;
+const {BrowserWindow} = require('electron').remote;
-var win = new BrowserWindow({ width: 800, height: 600 });
+let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('https://github.com');
```
// mapNumbers.js 메인 프로세스
exports.withRendererCallback = (mapper) => {
return [1,2,3].map(mapper);
-}
+;
exports.withLocalCallback = () => {
return exports.mapNumbers(x => x + 1);
-}
+};
```
```javascript
// 렌더러 프로세스
-const mapNumbers = require("remote").require("./mapNumbers");
+const mapNumbers = require('remote').require('./mapNumbers');
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1);
-const withLocalCb = mapNumbers.withLocalCallback()
+const withLocalCb = mapNumbers.withLocalCallback();
-console.log(withRendererCb, withLocalCb) // [true, true, true], [2, 3, 4]
+console.log(withRendererCb, withLocalCb); // [true, true, true], [2, 3, 4]
```
보다시피 동기적인 렌더러 콜백 함수의 반환 값은 예상되지 않은 값입니다. 그리고 메인
다음 예시는 화면 전체를 채우는 윈도우 창을 생성합니다:
```javascript
-const electron = require('electron');
-const { app, BrowserWindow } = electron;
+const {app, BrowserWindow, screen: electronScreen} = require('electron');
-let mainWindow;
+let win;
app.on('ready', () => {
- const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
- mainWindow = new BrowserWindow({ width, height });
+ let {width, height} = electronScreen.getPrimaryDisplay().workAreaSize;
+ win = new BrowserWindow({width, height});
});
```
다음 예시는 확장 디스플레이에 윈도우를 생성합니다:
```javascript
-const electron = require('electron');
-const { screen: electronScreen, app, BrowserWindow } = electron;
+const {app, BrowserWindow, screen: electronScreen} = require('electron');
-let mainWindow;
+let win;
app.on('ready', () => {
let displays = electronScreen.getAllDisplays();
let externalDisplay = null;
for (let i in displays) {
- if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) {
+ if (displays[i].bounds.x !== 0 || displays[i].bounds.y !== 0) {
externalDisplay = displays[i];
break;
}
}
if (externalDisplay) {
- mainWindow = new BrowserWindow({
+ win = new BrowserWindow({
x: externalDisplay.bounds.x + 50,
y: externalDisplay.bounds.y + 50
});
[`webContents`](web-contents.md)에서 `session` 속성으로 접근할 수도 있습니다.
```javascript
-const { BrowserWindow } = require('electron');
+const {BrowserWindow} = require('electron');
-let win = new BrowserWindow({ width: 800, height: 600 });
-win.loadURL("http://github.com");
+let win = new BrowserWindow({width: 800, height: 600});
+win.loadURL('http://github.com');
-const ses = win.webContents.session;
+let ses = win.webContents.session;
```
## Methods
});
// url에 관련된 쿠키를 모두 가져옵니다.
-session.defaultSession.cookies.get({ url : "http://www.github.com" }, (error, cookies) => {
+session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => {
console.log(cookies);
});
// 지정한 쿠키 데이터를 설정합니다.
// 동일한 쿠키가 있으면 해당 쿠키를 덮어씁니다.
-const cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" };
+const cookie = {url: 'http://www.github.com', name: 'dummy_name', value: 'dummy'};
session.defaultSession.cookies.set(cookie, (error) => {
if (error)
console.error(error);
```javascript
session.fromPartition(partition).setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === host) {
- if (permission === "notifications") {
+ if (permission === 'notifications') {
callback(false); // 거부됨.
return;
}
```javascript
// 다음 url에 대한 User Agent를 조작합니다.
const filter = {
- urls: ["https://*.github.com/*", "*://electron.github.io"]
+ urls: ['https://*.github.com/*', '*://electron.github.io']
};
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
다음 예시는 설정된 URL을 유저의 기본 브라우저로 엽니다:
```javascript
-const { shell } = require('electron');
+const {shell} = require('electron');
shell.openExternal('https://github.com');
```
메인 프로세스 스크립트는 일반 Node.js 스크립트와 비슷합니다:
```javascript
-const { app, BrowserWindow } = require('electron');
+const {app, BrowserWindow} = require('electron');
-let window = null;
+let win = null;
app.on('ready', () => {
- window = new BrowserWindow({width: 800, height: 600});
- window.loadURL('https://github.com');
+ win = new BrowserWindow({width: 800, height: 600});
+ win.loadURL('https://github.com');
});
```
<html>
<body>
<script>
- const { remote } = require('electron');
- console.log(remote.app.getVersion());
+ const {app} = require('electron').remote;
+ console.log(app.getVersion());
</script>
</body>
</html>
직관적으로 사용할 수 있습니다:
```javascript
-const { app, BrowserWindow } = require('electron');
+const {app, BrowserWindow} = require('electron');
```
모든 `electron` 모듈이 필요하다면, 먼저 require한 후 각 독립적인 모듈을
```javascript
const electron = require('electron');
-const { app, BrowserWindow } = electron;
+const {app, BrowserWindow} = electron;
```
위 코드는 다음과 같습니다:
또는 `hideInternalModules` API를 사용해도 됩니다:
```javascript
-require('electron').hideInternalModules()
+require('electron').hideInternalModules();
```
[gui]: https://en.wikipedia.org/wiki/Graphical_user_interface
예시입니다 (투명한 윈도우는 DWM 컴포지션이 비활성화되어있을 시 작동하지 않습니다):
```javascript
-let browserOptions = { width: 1000, height: 800 };
+let browserOptions = {width: 1000, height: 800};
// 플랫폼이 지원하는 경우에만 투명 윈도우를 생성.
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {
> 아이콘과 컨텍스트 메뉴를 시스템 알림 영역에 추가합니다.
```javascript
-const { app, Menu, Tray } = require('electron');
+const {app, Menu, Tray} = require('electron');
let appIcon = null;
app.on('ready', () => {
appIcon = new Tray('/path/to/my/icon'); // 현재 어플리케이션 디렉터리를 기준으로 하려면 `__dirname + '/images/tray.png'` 형식으로 입력해야 합니다.
const contextMenu = Menu.buildFromTemplate([
- { label: 'Item1', type: 'radio' },
- { label: 'Item2', type: 'radio' },
- { label: 'Item3', type: 'radio', checked: true },
- { label: 'Item4', type: 'radio' }
+ {label: 'Item1', type: 'radio'},
+ {label: 'Item2', type: 'radio'},
+ {label: 'Item3', type: 'radio', checked: true},
+ {label: 'Item4', type: 'radio'}
]);
appIcon.setToolTip('이것은 나의 어플리케이션 입니다!');
appIcon.setContextMenu(contextMenu);
접근하는 예시입니다:
```javascript
-const { BrowserWindow } = require('electron');
+const BrowserWindow = require('electron').BrowserWindow;
let win = new BrowserWindow({width: 800, height: 1500});
-win.loadURL("http://github.com");
+win.loadURL('http://github.com');
let webContents = win.webContents;
```
이 이벤트는 `did-finish-load`와 비슷하나, 로드가 실패했거나 취소되었을 때 발생합니다.
예를 들면 `window.stop()`이 실행되었을 때 발생합니다. 발생할 수 있는 전체 에러 코드의
목록과 설명은 [여기](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h)서
-확인할 수 있습니다. 참고로 리다이렉트 응답은 `errorCode` -3과 함께 발생합니다; 이
-에러는 명시적으로 무시할 수 있습니다.
+확인할 수 있습니다.
### Event: 'did-frame-finish-load'
* `issuerName` String - 인증서 발급자 이름
* `callback` Function
-클라이언트 인증이 요청되었을 때 발생하는 이벤트입니다.
+클라이언트 인증이 요청되었을 때 발생하는 이벤트 입니다.
사용법은 [`app`의 `select-client-certificate` 이벤트](app.md#event-select-client-certificate)와
같습니다.
* `image` NativeImage (optional)
* `scale` Float (optional)
-커서 타입이 변경될 때 발생하는 이벤트입니다. `type` 인수는 다음 값이 될 수 있습니다:
+커서 타입이 변경될 때 발생하는 이벤트입니다. `type` 매개변수는 다음 값이 될 수 있습니다:
`default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`,
`ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`,
`ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`,
`cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`,
`not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing`, `custom`.
-만약 `type` 인수가 `custom` 이고 `image` 인수가 `NativeImage`를 통한 커스텀
-커서를 지정했을 때, 해당 이미지로 커서가 변경됩니다. 또한 `scale` 인수는 이미지의
+만약 `type` 매개변수가 `custom` 이고 `image` 매개변수가 `NativeImage`를 통한 커스텀
+커서를 지정했을 때, 해당 이미지로 커서가 변경됩니다. 또한 `scale` 매개변수는 이미지의
크기를 조정합니다.
-### Event: 'context-menu'
-
-Returns:
-
-* `event` Event
-* `params` Object
- * `x` Integer - x 좌표
- * `y` Integer - y 좌표
- * `linkURL` String - 컨텍스트 메뉴가 호출된 노드를 둘러싸는 링크의 URL.
- * `linkText` String - 링크에 연관된 텍스트. 콘텐츠의 링크가 이미지인 경우 빈
- 문자열이 됩니다.
- * `pageURL` String - 컨텍스트 메뉴가 호출된 상위 수준 페이지의 URL.
- * `frameURL` String - 컨텍스트 메뉴가 호출된 서브 프레임의 URL.
- * `srcURL` String - 컨텍스트 메뉴가 호출된 요소에 대한 소스 URL. 요소와 소스 URL은
- 이미지, 오디오, 비디오입니다.
- * `mediaType` String - 컨텍스트 메뉴가 호출된 노드의 타입. 값은 `none`, `image`,
- `audio`, `video`, `canvas`, `file` 또는 `plugin`이 될 수 있습니다.
- * `mediaFlags` Object - 컨텍스트 메뉴가 호출된 미디어 요소에 대한 인수들.
- * `inError` - Boolean
- * `isPaused` - Boolean
- * `isMuted` - Boolean
- * `hasAudio` - Boolean
- * `isLooping` - Boolean
- * `isControlsVisible` - Boolean
- * `canToggleControls` - Boolean
- * `canRotate` - Boolean
- * `hasImageContent` Boolean - 컨텍스트 메뉴가 내용이 있는 이미지에서 호출되었는지
- 여부.
- * `isEditable` Boolean - 컨텍스트를 편집할 수 있는지 여부.
- * `editFlags` Object - 이 플래그는 랜더러가 다음 행동을 취할 수 있는지 여부를
- 표시합니다.
- * `canUndo` - Boolean
- * `canRedo` - Boolean
- * `canCut` - Boolean
- * `canCopy` - Boolean
- * `canPaste` - Boolean
- * `canDelete` - Boolean
- * `canSelectAll` - Boolean
- * `selectionText` String - 컨텍스트 메뉴가 호출된 부분에 있는 선택된 텍스트.
- * `titleText` String - 컨텍스트 메뉴가 호출된 선택된 제목 또는 알림 텍스트.
- * `misspelledWord` String - 만약 있는 경우, 커서가 가르키는 곳에서 발생한 오타.
- * `frameCharset` String - 메뉴가 호출된 프레임의 문자열 인코딩.
- * `inputFieldType` String - 컨텍스트 메뉴가 입력 필드에서 호출되었을 때, 그 필드의
- 타입. 값은 `none`, `plainText`, `password`, `other` 중 한 가지가 될 수 있습니다.
- * `menuSourceType` String - 컨텍스트 메뉴를 호출한 입력 소스. 값은 `none`,
- `mouse`, `keyboard`, `touch`, `touchMenu` 중 한 가지가 될 수 있습니다.
-
-새로운 컨텍스트 메뉴의 제어가 필요할 때 발생하는 이벤트입니다.
-
## Instance Methods
`webContents`객체는 다음과 같은 인스턴스 메서드들을 가지고 있습니다.
하는 경우 `pragma` 헤더를 사용할 수 있습니다.
```javascript
-const options = {"extraHeaders" : "pragma: no-cache\n"}
+const options = {extraHeaders: 'pragma: no-cache\n'};
webContents.loadURL(url, options)
```
```javascript
let win = new BrowserWindow({width: 800, height: 600});
-win.loadURL("http://github.com");
+win.loadURL('http://github.com');
let currentURL = win.webContents.getURL();
```
제공된 `action`에 대한 `webContents`의 모든 `findInPage` 요청을 중지합니다.
```javascript
-webContents.on('found-in-page', function(event, result) {
+webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate)
- webContents.stopFindInPage("clearSelection");
+ webContents.stopFindInPage('clearSelection');
});
-const requestId = webContents.findInPage("api");
+const requestId = webContents.findInPage('api');
```
### `webContents.hasServiceWorker(callback)`
### `webContents.printToPDF(options, callback)`
* `options` Object
- * `marginsType` Integer - 사용할 마진의 타입을 지정합니다. 0 부터 2 사이 값을 사용할
+ * `marginsType` Integer - 사용할 마진의 종류를 지정합니다. 0 부터 2 사이 값을 사용할
수 있고 각각 기본 마진, 마진 없음, 최소 마진입니다.
* `pageSize` String - 생성되는 PDF의 페이지 크기를 지정합니다. 값은 `A3`, `A4`,
`A5`, `Legal`, `Letter` 와 `Tabloid`가 사용될 수 있습니다.
* `printSelectionOnly` Boolean - 선택된 영역만 프린트할지 여부를 정합니다.
* `landscape` Boolean - landscape을 위해선 `true`를, portrait를 위해선 `false`를
사용합니다.
-* `callback` Function - `function(error, data) {}`
+* `callback` Function - `(error, data) => {}`
Chromium의 미리보기 프린팅 커스텀 설정을 이용하여 윈도우의 웹 페이지를 PDF로
프린트합니다.
```
```javascript
-const { BrowserWindow } = require('electron');
+const BrowserWindow = require('electron').BrowserWindow;
const fs = require('fs');
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('http://github.com');
win.webContents.on('did-finish-load', () => {
- // 기본 프린트 옵션을 사용합니다
+ // Use default printing options
win.webContents.printToPDF({}, (error, data) => {
if (error) throw error;
fs.writeFile('/tmp/print.pdf', data, (error) => {
이후에 사용해야 합니다.
```javascript
-mainWindow.webContents.on('devtools-opened', function() {
- mainWindow.webContents.addWorkSpace(__dirname);
+win.webContents.on('devtools-opened', () => {
+ win.webContents.addWorkSpace(__dirname);
});
```
* `options` Object (optional)
* `detach` Boolean - 새 창에서 개발자 도구를 엽니다.
- * `mode` String - 개발자 도구를 지정한 도킹 상태와 함께 엽니다. 옵션은 `right`,
- `bottom`, `undocked`, `detach`가 될 수 있습니다. 기본값은 마지막 표시 상태를
- ì\82¬ì\9a©í\95©ë\8b\88ë\8b¤. `undocked` 모ë\93\9cì\97\90ì\84 ë\8b¤ì\8b\9c ë\8f\84í\82¹을 할 수 있습니다. 하지만 `detach`
+ * `mode` String - 개발자 도구 표시 상태를 지정합니다. 옵션은 "right", "bottom",
+ "undocked", "detach"가 될 수 있습니다. 기본값은 마지막 표시 상태를
+ ì\82¬ì\9a©í\95©ë\8b\88ë\8b¤. `undocked` 모ë\93\9cì\97\90ì\84 ë\8b¤ì\8b\9c ë\8f\85을 할 수 있습니다. 하지만 `detach`
모드에선 할 수 없습니다.
개발자 도구를 엽니다.
메인 프로세스에서 렌더러 프로세스로 메시지를 보내는 예시 입니다:
```javascript
-// 메인 프로세스에서.
-let mainWindow = null;
-
+// In the main process.
+let win = null;
app.on('ready', () => {
- mainWindow = new BrowserWindow({width: 800, height: 600});
- mainWindow.loadURL(`file://${__dirname}/index.html`);
- mainWindow.webContents.on('did-finish-load', () => {
- mainWindow.webContents.send('ping', 'whoooooooh!');
+ win = new BrowserWindow({width: 800, height: 600});
+ win.loadURL('file://' + __dirname + '/index.html');
+ win.webContents.on('did-finish-load', () => {
+ win.webContents.send('ping', 'whoooooooh!');
});
});
```
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
- console.log(message); // "whoooooooh!" 출력
+ console.log(message); // Prints "whoooooooh!"
});
</script>
</body>
* `HTMLOnly` - 페이지의 HTML만 저장합니다.
* `HTMLComplete` - 페이지의 완성된 HTML을 저장합니다.
* `MHTML` - 페이지의 완성된 HTML을 MHTML로 저장합니다.
-* `callback` Function - `function(error) {}`.
+* `callback` Function - `(error) => {}`.
* `error` Error
만약 페이지를 저장하는 프로세스가 성공적으로 끝났을 경우 true를 반환합니다.
win.webContents.on('did-finish-load', () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
if (!error)
- console.log("Save page successfully");
+ console.log('Save page successfully');
});
});
```
```javascript
try {
- win.webContents.debugger.attach("1.1");
+ win.webContents.debugger.attach('1.1');
} catch(err) {
- console.log("Debugger attach failed : ", err);
+ console.log('Debugger attach failed : ', err);
};
win.webContents.debugger.on('detach', (event, reason) => {
- console.log("Debugger detached due to : ", reason);
+ console.log('Debugger detached due to : ', reason);
});
win.webContents.debugger.on('message', (event, method, params) => {
- if (method === "Network.requestWillBeSent") {
- if (params.request.url === "https://www.github.com")
+ if (method === 'Network.requestWillBeSent') {
+ if (params.request.url === 'https://www.github.com')
win.webContents.debugger.detach();
}
-})
+});
-win.webContents.debugger.sendCommand("Network.enable");
+win.webContents.debugger.sendCommand('Network.enable');
```
#### `webContents.debugger.attach([protocolVersion])`
* `method` String - 메서드 이름, 반드시 원격 디버깅 프로토콜에 의해 정의된 메서드중
하나가 됩니다.
-* `commandParams` Object (optional) - 요청 인수를 표현한 JSON 객체.
+* `commandParams` Object (optional) - 요청 매개변수를 표현한 JSON 객체.
* `callback` Function (optional) - 응답
* `error` Object - 커맨드의 실패를 표시하는 에러 메시지.
* `result` Object - 원격 디버깅 프로토콜에서 커맨드 설명의 'returns' 속성에 의해
* `event` Event
* `method` String - 메서드 이름.
-* `params` Object - 원격 디버깅 프로토콜의 'parameters' 속성에서 정의된 이벤트 인수
+* `params` Object - 원격 디버깅 프로토콜의 'parameters' 속성에서 정의된 이벤트
+ 매개변수
디버깅 타겟이 관련 이벤트를 발생시킬 때 마다 발생하는 이벤트입니다.
다음 예시는 현재 페이지를 200% 줌 합니다:
```javascript
-const { webFrame } = require('electron');
+const {webFrame} = require('electron');
webFrame.setZoomFactor(2);
```
[node-spellchecker][spellchecker]를 철자 검사 제공자로 사용하는 예시입니다:
```javascript
-webFrame.setSpellCheckProvider("en-US", true, {
- spellCheck: function(text) {
+webFrame.setSpellCheckProvider('en-US', true, {
+ spellCheck(text) {
return !(require('spellchecker').isMisspelled(text));
}
});
const loadstart = () => {
indicator.innerText = 'loading...';
- }
+ };
const loadstop = () => {
indicator.innerText = '';
- }
+ };
webview.addEventListener('did-start-loading', loadstart);
webview.addEventListener('did-stop-loading', loadstop);
- }
+ };
</script>
```
**예시**
```javascript
-webview.addEventListener("dom-ready", () => {
+webview.addEventListener('dom-ready', () => {
webview.openDevTools();
});
```
콘솔에 다시 로깅하는 예시입니다.
```javascript
-webview.addEventListener('console-message', function(e) {
+webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message);
});
```
사용할 수 있을 때 발생하는 이벤트입니다.
```javascript
-webview.addEventListener('found-in-page', function(e) {
+webview.addEventListener('found-in-page', (e) => {
if (e.result.finalUpdate)
- webview.stopFindInPage("keepSelection");
+ webview.stopFindInPage('keepSelection');
});
-const rquestId = webview.findInPage("test");
+const rquestId = webview.findInPage('test');
```
### Event: 'new-window'
다음 예시 코드는 새 URL을 시스템의 기본 브라우저로 여는 코드입니다.
```javascript
-const { shell } = require('electron');
+const {shell} = require('electron');
webview.addEventListener('new-window', (e) => {
const protocol = require('url').parse(e.url).protocol;
```javascript
// In guest page.
-var { ipcRenderer } = require('electron');
+const {ipcRenderer} = require('electron');
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong');
});
```javascript
app.on('ready', () => {
const tray = new Tray('/path/to/icon.png');
-})
+});
```
를 이렇게:
let tray = null;
app.on('ready', () => {
tray = new Tray('/path/to/icon.png');
-})
+});
```
## Electron에서 jQuery/RequireJS/Meteor/AngularJS를 사용할 수 없습니다.
```javascript
// 메인 프로세스에서.
-let mainWindow = new BrowserWindow({
+let win = new BrowserWindow({
webPreferences: {
nodeIntegration: false
}
```javascript
Alarm.on('wake-up', (time) => {
console.log(time)
-})
+});
```
`BrowserWindow` 클래스를 이용해 원하는 웹 페이지도 표시할 수 있습니다:
```javascript
-const { BrowserWindow } = require('electron');
+const {BrowserWindow} = require('electron');
let win = new BrowserWindow({width: 800, height: 600});
win.loadURL('file:///path/to/example.asar/static/index.html');
```
```html
<script>
-var $ = require('./jquery.min.js');
+let $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', (data) => {
console.log(data);
});
body: 'Lorem Ipsum Dolor Sit Amet'
});
-myNotification.onclick = function () {
- console.log('Notification clicked')
-}
+myNotification.onclick = () => {
+ console.log('Notification clicked');
+};
```
위 코드를 통해 생성한 데스크톱 알림은 각 운영체제 모두 비슷한 사용자 경험을 제공하지만,
OS X에서만 사용 가능합니다:
```javascript
-const electron = require('electron');
-const app = electron.app;
-const Menu = electron.Menu;
+const {app, Menu} = require('electron');
const dockMenu = Menu.buildFromTemplate([
- { label: 'New Window', click: () => { console.log('New Window'); } },
- { label: 'New Window with Settings', submenu: [
- { label: 'Basic' },
- { label: 'Pro'}
+ {label: 'New Window', click() { console.log('New Window'); }},
+ {label: 'New Window with Settings', submenu: [
+ {label: 'Basic'},
+ {label: 'Pro'}
]},
- { label: 'New Command...'}
+ {label: 'New Command...'}
]);
+
app.dock.setMenu(dockMenu);
```
미리보기 툴바를 설정할 수 있습니다:
```javascript
-const { BrowserWindow } = require('electron');
+const {BrowserWindow} = require('electron');
const path = require('path');
let win = new BrowserWindow({
win.setThumbarButtons([
{
- tooltip: "button1",
+ tooltip: 'button1',
icon: path.join(__dirname, 'button1.png'),
- click: () => { console.log("button2 clicked"); }
+ click() { console.log('button2 clicked'); }
},
{
- tooltip: "button2",
+ tooltip: 'button2',
icon: path.join(__dirname, 'button2.png'),
flags:['enabled', 'dismissonclick'],
- click: () => { console.log("button2 clicked."); }
+ click() { console.log('button2 clicked.'); }
}
]);
```
있습니다:
```javascript
-let window = new BrowserWindow({...});
-window.setProgressBar(0.5);
+let win = new BrowserWindow({...});
+win.setProgressBar(0.5);
```
## 작업 표시줄의 아이콘 오버레이 (Windows)
API를 사용할 수 있습니다:
```javascript
-let window = new BrowserWindow({...});
-window.setOverlayIcon('path/to/overlay.png', 'Description for overlay');
+let win = new BrowserWindow({...});
+win.setOverlayIcon('path/to/overlay.png', 'Description for overlay');
```
## 대표 파일 제시 (OS X)
[BrowserWindow.setDocumentEdited][setdocumentedited]를 사용할 수 있습니다:
```javascript
-let window = new BrowserWindow({...});
-window.setRepresentedFilename('/etc/passwd');
-window.setDocumentEdited(true);
+let win = new BrowserWindow({...});
+win.setRepresentedFilename('/etc/passwd');
+win.setDocumentEdited(true);
```
[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath-os-x-windows
_main.js_
```javascript
-const electron = require('electron');
-const app = electron.app;
-const BrowserWindow = electron.BrowserWindow;
+const {app, BrowserWindow} = require('electron');
let onlineStatusWindow;
app.on('ready', () => {
- onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
+ onlineStatusWindow = new BrowserWindow({width: 0, height: 0, show: false});
onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html');
});
```
_main.js_
```javascript
-const electron = require('electron');
-const app = electron.app;
-const ipcMain = electron.ipcMain;
-const BrowserWindow = electron.BrowserWindow;
+const {app, ipcMain, BrowserWindow} = require('electron');
let onlineStatusWindow;
app.on('ready', () => {
- onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
+ onlineStatusWindow = new BrowserWindow({width: 0, height: 0, show: false});
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});
<html>
<body>
<script>
- const { ipcRenderer } = require('electron');
+ const {ipcRenderer} = require('electron');
const updateOnlineStatus = () => {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};
```javascript
const electron = require('electron');
// 어플리케이션 생명주기를 조작 하는 모듈.
-const app = electron.app;
+const {app} = electron;
// 네이티브 브라우저 창을 만드는 모듈.
-const BrowserWindow = electron.BrowserWindow;
+const {BrowserWindow} = electron;
// 윈도우 객체를 전역에 유지합니다. 만약 이렇게 하지 않으면
// 자바스크립트 GC가 일어날 때 창이 멋대로 닫혀버립니다.
-let mainWindow;
+let win;
function createWindow () {
// 새로운 브라우저 창을 생성합니다.
- mainWindow = new BrowserWindow({width: 800, height: 600});
+ win = new BrowserWindow({width: 800, height: 600});
// 그리고 현재 디렉터리의 index.html을 로드합니다.
- mainWindow.loadURL(`file://${__dirname}/index.html`);
+ win.loadURL(`file://${__dirname}/index.html`);
// 개발자 도구를 엽니다.
- mainWindow.webContents.openDevTools();
+ win.webContents.openDevTools();
// 창이 닫히면 호출됩니다.
- mainWindow.on('closed', () => {
+ win.on('closed', () => {
// 윈도우 객체의 참조를 삭제합니다. 보통 멀티 윈도우 지원을 위해
// 윈도우 객체를 배열에 저장하는 경우가 있는데 이 경우
// 해당하는 모든 윈도우 객체의 참조를 삭제해 주어야 합니다.
- mainWindow = null;
+ win = null;
});
}
app.on('activate', () => {
// OS X에선 보통 독 아이콘이 클릭되고 나서도
// 열린 윈도우가 없으면, 새로운 윈도우를 다시 만듭니다.
- if (mainWindow === null) {
+ if (win === null) {
createWindow();
}
});
app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169');
app.on('ready', () => {
- mainWindow = new BrowserWindow({
+ win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
plugins: true
}
});
- mainWindow.loadURL(`file://${__dirname}/index.html`);
+ win.loadURL(`file://${__dirname}/index.html`);
// 이외의 코드
});
```
```javascript
const webdriverio = require('webdriverio');
let options = {
- host: "localhost", // localhost에서 작동중인 크롬 드라이버 서버를 사용합니다.
+ host: 'localhost', // localhost에서 작동중인 크롬 드라이버 서버를 사용합니다.
port: 9515, // 연결할 크롬 드라이버 서버의 포트를 설정합니다.
desiredCapabilities: {
browserName: 'chrome',
// 플러그인의 버전은 크롬의 `chrome://plugins` 페이지에서 취득할 수 있습니다.
app.commandLine.appendSwitch('widevine-cdm-version', '1.4.8.866');
-let mainWindow = null;
+let win = null;
app.on('ready', () => {
- mainWindow = new BrowserWindow({
+ win = new BrowserWindow({
webPreferences: {
// `plugins`은 활성화되어야 합니다.
plugins: true
}
- })
+ });
});
```