Перейти к основному содержанию

40 постов с тегом "версия"

Показать все теги

Node.js Native Addons and Electron 5.0

· 2 мин. прочитано

If you're having trouble using a native Node.js addon with Electron 5.0, there's a chance it needs to be updated to work with the most recent version of V8.


Goodbye v8::Handle, Hello v8::Local

In 2014, the V8 team deprecated v8::Handle in favor of v8::Local for local handles. Electron 5.0 includes a version of V8 that has finally removed v8::Handle for good, and native Node.js addons that still use it will need to be updated before they can be used with Electron 5.0.

The required code change is minimal, but every native Node module that still uses v8::Handle will fail to build with Electron 5.0 and will need to be modified. The good news is that Node.js v12 will also include this V8 change, so any modules that use v8::Handle will need to be updated anyway to work with the upcoming version of Node.

I maintain a native addon, how can I help?

If you maintain a native addon for Node.js, ensure you replace all occurrences of v8::Handle with v8::Local. The former was just an alias of the latter, so no other changes need to be made to address this specific issue.

You may also be interested in looking into N-API, which is maintained separately from V8 as a part of Node.js itself, and aims to insulate native addons from changes in the underlying JavaScript engine. You can find more information in the N-API documentation on the Node.js website.

Help! I use a native addon in my app and it won't work!

If you're consuming a native addon for Node.js in your app and the native addon will not build because of this issue, check with the author of the addon to see if they've released a new version that fixes the problem. If not, reaching out to the author (or opening a Pull Request!) is probably your best bet.

Electron v5.0.0 Timeline

· 2 мин. прочитано

Впервые Electron рад обнародовать график выпуска нашего релиза начиная с версии 5. .0 Это наш первый шаг на пути к общественности, долгосрочному графику.


As mentioned in our v4.0.0 stable release blog post, we are planning to release approximately quarterly to maintain closer cadence with Chromium releases. Chromium releases a new version very quickly -- every 6 weeks.

Take a look at progression in Electron versus Chromium side-by-side:

line graph comparing Electron versus Chromium versions

In the last half of 2018, our top priority was releasing faster and catching up closer to Chromium. We succeeded by sticking to a predetermined timeline. Electron 3.0.0 and 4.0.0 were released in a 2-3 month timeline for each release. We are optimistic about continuing that pace in releasing 5.0.0 and beyond. With a major Electron release approximately every quarter, we're now keeping pace with Chromium's release cadence. Getting ahead of Chromium stable release is always a goal for us and we are taking steps towards that.

We would love to promise future dates like Node.js and Chromium do, but we are not at that place yet. We are optimistic that we will reach a long-term timeline in the future.

С учетом этого мы предпринимаем первые шаги, опубликовав график выпуска v5.0.0. Вы можете найти этот здесь.

To help us with testing our beta releases and stabilization, please consider joining our App Feedback Program.

Electron 4.0.0

· 6 мин. прочитано

Команда Electron рада сообщить, что стабильный релиз Electron 4 теперь доступна! Вы можете установить его с electronjs.org или через npm через npm install electron@latest. Релиз наполнен улучшениями, исправлениями и новыми функциями, и мы не можем дождаться, чтобы посмотреть, что вы сможете с ними сделать. Читайте дальше для подробностей об этом релизе, и, пожалуйста, поделитесь своим мнением, которое у вас появится по мере изучения!


What's New?

Большая часть функциональности Electron обеспечивается Chromium, Node.js и V8, основными компонентами, из которых состоит Electron. As such, a key goal for the Electron team is to keep up with changes to these projects as much as possible, providing developers who build Electron apps access to new web and JavaScript features. To this end, Electron 4 features major version bumps to each of these components; Electron v4.0.0 includes Chromium 69.0.3497.106, Node 10.11.0, and V8 6.9.427.24.

In addition, Electron 4 includes changes to Electron-specific APIs. You can find a summary of the major changes in Electron 4 below; for the full list of changes, check out the Electron v4.0.0 release notes.

Disabling the remote Module

You now have the ability to disable the remote module for security reasons. The module can be disabled for BrowserWindows and for webview tags:

// BrowserWindow
new BrowserWindow({
webPreferences: {
enableRemoteModule: false
}
})

// webview tag
<webview src="http://www.google.com/" enableremotemodule="false"></webview>

See the BrowserWindow and <webview> Tag documentation for more information.

Filtering remote.require() / remote.getGlobal() Requests

This feature is useful if you don't want to completely disable the remote module in your renderer process or webview but would like additional control over which modules can be required via remote.require.

When a module is required via remote.require in a renderer process, a remote-require event is raised on the app module. You can call event.preventDefault() on the the event (the first argument) to prevent the module from being loaded. The WebContents instance where the require occurred is passed as the second argument, and the name of the module is passed as the third argument. The same event is also emitted on the WebContents instance, but in this case the only arguments are the event and the module name. In both cases, you can return a custom value by setting the value of event.returnValue.

// Control `remote.require` from all WebContents:
app.on('remote-require', function (event, webContents, requestedModuleName) {
// ...
});

// Control `remote.require` from a specific WebContents instance:
browserWin.webContents.on(
'remote-require',
function (event, requestedModuleName) {
// ...
}
);

In a similar fashion, when remote.getGlobal(name) is called, a remote-get-global event is raised. This works the same way as the remote-require event: call preventDefault() to prevent the global from being returned, and set event.returnValue to return a custom value.

// Control `remote.getGlobal` from all WebContents:
app.on(
'remote-get-global',
function (event, webContents, requrestedGlobalName) {
// ...
}
);

// Control `remote.getGlobal` from a specific WebContents instance:
browserWin.webContents.on(
'remote-get-global',
function (event, requestedGlobalName) {
// ...
}
);

For more information, see the following documentation:

JavaScript Access to the About Panel

On macOS, you can now call app.showAboutPanel() to programmatically show the About panel, just like clicking the menu item created via {role: 'about'}. See the showAboutPanel documentation for more information

Controlling WebContents Background Throttling

WebContents instances now have a method setBackgroundThrottling(allowed) to enable or disable throttling of timers and animations when the page is backgrounded.

let win = new BrowserWindow(...)
win.webContents.setBackgroundThrottling(enablegroundThrottling)
win.webContents.setBackgroundThrottling(enableBackgroundThrottling)

See the setBackgroundThrottling documentation for more information.

Критические изменения

No More macOS 10.9 Support

Chromium no longer supports macOS 10.9 (OS X Mavericks), and as a result Electron 4.0 and beyond does not support it either.

Single Instance Locking

Previously, to make your app a Single Instance Application (ensuring that only one instance of your app is running at any given time), you could use the app.makeSingleInstance() method. Starting in Electron 4.0, you must use app.requestSingleInstanceLock() instead. The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately.

For an example of using requestSingleInstanceLock() and information on nuanced behavior on various platforms, see the documentation for app.requestSingleInstanceLock() and related methods and the second-instance event.

win_delay_load_hook

When building native modules for windows, the win_delay_load_hook variable in the module's binding.gyp must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like Cannot find module. See the native module guide for more information.

Deprecations

The following breaking changes are planned for Electron 5.0, and thus are deprecated in Electron 4.0.

Node.js Integration Disabled for nativeWindowOpen-ed Windows

Starting in Electron 5.0, child windows opened with the nativeWindowOpen option will always have Node.js integration disabled.

webPreferences Default Values

When creating a new BrowserWindow with the webPreferences option set, the following webPreferences option defaults are deprecated in favor of new defaults listed below:

PropertyDeprecated DefaultNew Default
contextIsolationfalsetrue
nodeIntegrationtruefalse
webviewTagvalue of nodeIntegration if set, otherwise truefalse

Please note: there is currently a known bug (#9736) that prevents the webview tag from working if contextIsolation is on. Keep an eye on the GitHub issue for up-to-date information!

Learn more about context isolation, Node integration, and the webview tag in the Electron security document.

Electron 4.0 will still use the current defaults, but if you don't pass an explicit value for them, you'll see a deprecation warning. To prepare your app for Electron 5.0, use explicit values for these options. See the BrowserWindow docs for details on each of these options.

webContents.findInPage(text[, options])

The medialCapitalAsWordStart and wordStart options have been deprecated as they have been removed upstream.

Программа отзывов

The App Feedback Program we instituted during the development of Electron 3.0 was successful, so we've continued it during the development of 4.0 as well. We'd like to extend a massive thank you to Atlassian, Discord, MS Teams, OpenFin, Slack, Symphony, WhatsApp, and the other program members for their involvement during the 4.0 beta cycle. To learn more about the App Feedback Program and to participate in future betas, check out our blog post about the program.

Что дальше

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8. Although we are careful not to make promises about release dates, our plan is release new major versions of Electron with new versions of those components approximately quarterly. See our versioning document for more detailed information about versioning in Electron.

For information on planned breaking changes in upcoming versions of Electron, see our Planned Breaking Changes doc.

Electron 3.0.0

· 4 мин. прочитано

The Electron team is excited to announce that the first stable release of Electron 3 is now available from electronjs.org and via npm install electron@latest! It's jam-packed with upgrades, fixes, and new features, and we can't wait to see what you build with them. Below are details about this release, and we welcome your feedback as you explore.


Release Process

As we undertook development of v3.0.0, we sought to more empirically define criteria for a stable release by formalizing the feedback progress for progressive beta releases. v3.0.0 would not have been possible without our App Feedback Program partners, who provided early testing and feedback during the beta cycle. Thanks to Atlassian, Atom, Microsoft Teams, Oculus, OpenFin, Slack, Symphony, VS Code, and other program members for their work. If you'd like to participate in future betas, please mail us at info@electronjs.org.

Changes / New Features

Major bumps to several important parts of Electron's toolchain, including Chrome v66.0.3359.181, Node v10.2.0, and V8 v6.6.346.23.

  • [#12656] feat: app.isPackaged
  • [#12652] feat: app.whenReady()
  • [#13183] feat: process.getHeapStatistics()
  • [#12485] feat: win.moveTop() to move window z-order to top
  • [#13110] feat: TextField and Button APIs
  • [#13068] feat: netLog API for dynamic logging control
  • [#13539] feat: enable webview in sandbox renderer
  • [#14118] feat: fs.readSync now works with massive files
  • [#14031] feat: node fs wrappers to make fs.realpathSync.native and fs.realpath.native available

Breaking API changes

  • [#12362] feat: updates to menu item order control
  • [#13050] refactor: removed documented deprecated APIs
    • See docs for more details
  • [#12477] refactor: removed did-get-response-details and did-get-redirect-request events
  • [#12655] feat: default to disabling navigating on drag/drop
  • [#12993] feat: Node v4.x or greater is required use the electron npm module
  • [#12008 #12140 #12503 #12514 #12584 #12596 #12637 #12660 #12696 #12716 #12750 #12787 #12858] refactor: NativeWindow
  • [#11968] refactor: menu.popup()
  • [#8953] feat: no longer use JSON to send the result of ipcRenderer.sendSync
  • [#13039] feat: default to ignore command line arguments following a URL
  • [#12004] refactor: rename api::Window to api::BrowserWindow
  • [#12679] feat: visual zoom now turned off by default
  • [#12408] refactor: rename app-command media-play_pause to media-play-pause

macOS

  • [#12093] feat: workspace notifications support
  • [#12496] feat: tray.setIgnoreDoubleClickEvents(ignore) to ignore tray double click events.
  • [#12281] feat: mouse forward functionality on macOS
  • [#12714] feat: screen lock / unlock events

Windows

  • [#12879] feat: added DIP to/from screen coordinate conversions

Nota Bene: Switching to an older version of Electron after running this version will require you to clear out your user data directory to avoid older versions crashing. You can get the user data directory by running console.log(app.getPath("userData")) or see docs for more details.

Bug Fixes

  • [#13397] fix: issue with fs.statSyncNoException throwing exceptions
  • [#13476, #13452] fix: crash when loading site with jquery
  • [#14092] fix: crash in net::ClientSocketHandle destructor
  • [#14453] fix: notify focus change right away rather not on next tick

MacOS

  • [#13220] fix: issue allowing bundles to be selected in <input file="type"> open file dialog
  • [#12404] fix: issue blocking main process when using async dialog
  • [#12043] fix: context menu click callback
  • [#12527] fix: event leak on reuse of touchbar item
  • [#12352] fix: tray title crash
  • [#12327] fix: non-draggable regions
  • [#12809] fix: to prevent menu update while it's open
  • [#13162] fix: tray icon bounds not allowing negative values
  • [#13085] fix: tray title not inverting when highlighted
  • [#12196] fix: Mac build when enable_run_as_node==false
  • [#12157] fix: additional issues on frameless windows with vibrancy
  • [#13326] fix: to set mac protocol to none after calling app.removeAsDefaultProtocolClient
  • [#13530] fix: incorrect usage of private APIs in MAS build
  • [#13517] fix: tray.setContextMenu crash
  • [#14205] fix: pressing escape on a dialog now closes it even if defaultId is set

Linux

  • [#12507] fix: BrowserWindow.focus() for offscreen windows

Other Notes

  • PDF Viewer is currently not working but is being worked on and will be functional once again soon
  • TextField and Button APIs are experimental and are therefore off by default
    • They can be enabled with the enable_view_api build flag

Что дальше

The Electron team continues to work on defining our processes for more rapid and smooth upgrades as we seek to ultimately maintain parity with the development cadences of Chromium, Node, and V8.

Electron 2.0.0

· 5 мин. прочитано

After more than four months of development, eight beta releases, and worldwide testing from many apps' staged rollouts, the release of Electron 2.0.0 is now available from electronjs.org.


Release Process

Starting with 2.0.0, Electron's releases will follow semantic versioning. This means the major version will bump more often and will usually be a major update to Chromium. Patch releases should be more stable because they will contain only high-priority bug fixes.

Electron 2.0.0 also represents an improvement to how Electron is stabilized before a major release. Several large scale Electron apps have included 2.0.0 betas in staged rollouts, providing the best feedback loop Electron's ever had for a beta series.

Changes / New Features

  • Major bumps to several important parts of Electron's toolchain, including Chrome 61, Node 8.9.3, V8 6.1.534.41, GTK+ 3 on Linux, updated spellchecker, and Squirrel.
  • In-app purchases are now supported on MacOS. #11292
  • New API for loading files. #11565
  • New API to enable/disable a window. #11832
  • New API app.setLocale(). #11469
  • New support for logging IPC messages. #11880
  • New menu events. #11754
  • Add a shutdown event to powerMonitor. #11417
  • Add affinity option for gathering several BrowserWindows into a single process. #11501
  • Add the ability for saveDialog to list available extensions. #11873
  • Support for additional notification actions #11647
  • The ability to set macOS notification close button title. #11654
  • Add conditional for menu.popup(window, callback)
  • Memory improvements in touchbar items. #12527
  • Improved security recommendation checklist.
  • Add App-Scoped Security scoped bookmarks. #11711
  • Add ability to set arbitrary arguments in a renderer process. #11850
  • Add accessory view for format picker. #11873
  • Fixed network delegate race condition. #12053
  • Drop support for the mips64el arch on Linux. Electron requires the C++14 toolchain, which was not available for that arch at the time of the release. We hope to re-add support in the future.

Breaking API changes

  • Removed deprecated APIs, including:
    • Changed menu.popup signature. #11968
    • Removed deprecated crashReporter.setExtraParameter #11972
    • Removed deprecated webContents.setZoomLevelLimits and webFrame.setZoomLevelLimits. #11974
    • Removed deprecated clipboard methods. #11973
    • Removed support for boolean parameters for tray.setHighlightMode. #11981

Bug Fixes

  • Changed to make sure webContents.isOffscreen() is always available. #12531
  • Fixed BrowserWindow.getFocusedWindow() when DevTools is undocked and focused. #12554
  • Fixed preload not loading in sandboxed render if preload path contains special chars. #12643
  • Correct the default of allowRunningInsecureContent as per docs. #12629
  • Fixed transparency on nativeImage. #12683
  • Fixed issue with Menu.buildFromTemplate. #12703
  • Confirmed menu.popup options are objects. #12330
  • Removed a race condition between new process creation and context release. #12361
  • Update draggable regions when changing BrowserView. #12370
  • Fixed menubar toggle alt key detection on focus. #12235
  • Fixed incorrect warnings in webviews. #12236
  • Fixed inheritance of 'show' option from parent windows. #122444
  • Ensure that getLastCrashReport() is actually the last crash report. #12255
  • Fixed require on network share path. #12287
  • Fixed context menu click callback. #12170
  • Fixed popup menu position. #12181
  • Improved libuv loop cleanup. #11465
  • Fixed hexColorDWORDToRGBA for transparent colors. #11557
  • Fixed null pointer dereference with getWebPreferences api. #12245
  • Fixed a cyclic reference in menu delegate. #11967
  • Fixed protocol filtering of net.request. #11657
  • WebFrame.setVisualZoomLevelLimits now sets user-agent scale constraints #12510
  • Set appropriate defaults for webview options. #12292
  • Improved vibrancy support. #12157 #12171 #11886
  • Fixed timing issue in singleton fixture.
  • Fixed broken production cache in NotifierSupportsActions()
  • Made MenuItem roles camelCase-compatible. #11532
  • Improved touch bar updates. #11812, #11761.
  • Removed extra menu separators. #11827
  • Fixed Bluetooth chooser bug. Closes #11399.
  • Fixed macos Full Screen Toggle menu item label. #11633
  • Improved tooltip hiding when a window is deactivated. #11644
  • Migrated deprecated web-view method. #11798
  • Fixed closing a window opened from a browserview. #11799
  • Fixed Bluetooth chooser bug. #11492
  • Updated to use task scheduler for app.getFileIcon API. #11595
  • Changed to fire console-message event even when rendering offscreen. #11921
  • Fixed downloading from custom protocols using WebContents.downloadURL. #11804
  • Fixed transparent windows losing transparency when devtools detaches. #11956
  • Fixed Electron apps canceling restart or shutdown. #11625

macOS

  • Fixed event leak on reuse of touchbar item. #12624
  • Fixed tray highlight in darkmode. #12398
  • Fixed blocking main process for async dialog. #12407
  • Fixed setTitle tray crash. #12356
  • Fixed crash when setting dock menu. #12087

Linux

Windows

  • Added Visual Studio 2017 support. #11656
  • Fixed passing of exception to the system crash handler. #12259
  • Fixed hiding tooltip from minimized window. #11644
  • Fixed desktopCapturer to capture the correct screen. #11664
  • Fixed disableHardwareAcceleration with transparency. #11704

Что дальше

The Electron team is hard at work to support newer versions of Chromium, Node, and v8. Expect 3.0.0-beta.1 soon!

Electron 2.0 and Beyond - Semantic Versioning

· Одна мин. чтения

A new major version of Electron is in the works, and with it some changes to our versioning strategy. As of version 2.0.0, Electron will strictly adhere to Semantic Versioning.


This change means you'll see the major version bump more often, and it will usually be a major update to Chromium. Patch releases will also be more stable, as they will now only contain bug fixes with no new features.

Major Version Increments

  • Chromium version updates
  • Node.js major version updates
  • Electron breaking API changes

Minor Version Increments

  • Node.js minor version updates
  • Electron non-breaking API changes

Patch Version Increments

  • Node.js patch version updates
  • fix-related chromium patches
  • Electron bug fixes

Because Electron's semver ranges will now be more meaningful, we recommend installing Electron using npm's default --save-dev flag, which will prefix your version with ^, keeping you safely up to date with minor and patch updates:

npm install --save-dev electron

For developers interested only in bug fixes, you should use the tilde semver prefix e.g. ~2.0.0, which which will never introduce new features, only fixes to improve stability.

For more details, see electronjs.org/docs/tutorial/electron-versioning.

Electron 1.0

· 3 мин. прочитано

For the last two years, Electron has helped developers build cross platform desktop apps using HTML, CSS, and JavaScript. Now we're excited to share a major milestone for our framework and for the community that created it. Выпуск Electron 1.0 теперь доступен в electronjs.org.


Electron 1.0

Electron 1.0 represents a major milestone in API stability and maturity. This release allows you to build apps that act and feel truly native on Windows, Mac, and Linux. Building Electron apps is easier than ever with new docs, new tools, and a new app to walk you through the Electron APIs.

Если вы готовы создать свое первое приложение Electron, вот быстрый старт поможет вам начать работу.

Нам не терпится увидеть, что вы создадите с Electron.

Путь Electron

Мы выпустили Electron, когда мы запустили Atom чуть более двух лет назад. Electron, тогда известный как Atom Shell, был фреймворком, на котором мы построили Atom. In those days, Atom was the driving force behind the features and functionalities that Electron provided as we pushed to get the initial Atom release out.

Теперь вождение Electron является растущим сообществом разработчиков и компаний строит все на основе электронной почты, чата, и Git-приложения для Инструменты аналитики SQL, клиентов торрентов, и робота.

In these last two years we've seen both companies and open source projects choose Electron as the foundation for their apps. Just in the past year, Electron has been downloaded over 1.2 million times. Ознакомьтесь с некоторыми из удивительных приложений Electron и добавьте свои собственные приложения, если они еще не там.

Скачать Electron

Демонстрации Electron API

Along with the 1.0 release, we're releasing a new app to help you explore the Electron APIs and learn more about how to make your Electron app feel native. Along with the 1.0 release, we're releasing a new app to help you explore the Electron APIs and learn more about how to make your Electron app feel native.

Демонстрации Electron API

Devtron

Мы также добавили новое расширение, которое поможет вам отлаживать ваши приложения Electron. Devtron является открытым исходным кодом расширением для Инструментов разработчика Chrome , призванных помочь вам проверить, отладка и устранение неполадок вашего приложения Electron.

Devtron

Функции

  • Require graph that helps you visualize your app's internal and external library dependencies in both the main and renderer processes
  • IPC monitor that tracks and displays the messages sent and received between the processes in your app
  • Event inspector that shows you the events and listeners that are registered in your app on the core Electron APIs such as the window, app, and processes
  • App Linter that checks your apps for common mistakes and missing functionality

Spectron

Наконец, мы выпускаем новую версию Spectron, интеграцию тестирования фреймворка для Electron приложений.

Spectron

Spectron 3.0 has comprehensive support for the entire Electron API allowing you to more quickly write tests that verify your application's behavior in various scenarios and environments. Спектр основан на ChromeDriver и WebDriverIO , поэтому у него также полные API для навигации по страницам, пользователь вводит и выполняет JavaScript.

Сообщество

Electron 1.0 is the result of a community effort by hundreds of developers. Outside of the core framework, there have been hundreds of libraries and tools released to make building, packaging, and deploying Electron apps easier.

Сейчас появилась новая страница сообщества с описанием многих замечательных инструментов Electron, приложений, библиотек и фреймворков. Вы также можете проверить Electron и Electron Userland , чтобы увидеть некоторые из этих фантастических проектов.

Впервые встречаете? Посмотрите вступительное видео Electron 1.0:

What's new in Electron 0.37

· 4 мин. прочитано

Electron 0.37 was recently released and included a major upgrade from Chrome 47 to Chrome 49 and also several new core APIs. This latest release brings in all the new features shipped in Chrome 48 and Chrome 49. This includes CSS custom properties, increased ES6 support, KeyboardEvent improvements, Promise improvements, and many other new features now available in your Electron app.


What's New

CSS Custom Properties

If you've used preprocessed languages like Sass and Less, you're probably familiar with variables, which allow you to define reusable values for things like color schemes and layouts. Variables help keep your stylesheets DRY and more maintainable.

CSS custom properties are similar to preprocessed variables in that they are reusable, but they also have a unique quality that makes them even more powerful and flexible: they can be manipulated with JavaScript. This subtle but powerful feature allows for dynamic changes to visual interfaces while still benefitting from CSS's hardware acceleration, and reduced code duplication between your frontend code and stylesheets.

For more info on CSS custom properties, see the MDN article and the Google Chrome demo.

CSS Variables In Action

Let's walk through a simple variable example that can be tweaked live in your app.

:root {
--awesome-color: #a5ecfa;
}

body {
background-color: var(--awesome-color);
}

The variable value can be retrieved and changed directly in JavaScript:

// Get the variable value ' #A5ECFA'
let color = window
.getComputedStyle(document.body)
.getPropertyValue('--awesome-color');

// Set the variable value to 'orange'
document.body.style.setProperty('--awesome-color', 'orange');

The variable values can be also edited from the Styles section of the development tools for quick feedback and tweaks:

CSS properties in Styles tab

KeyboardEvent.code Property

Chrome 48 added the new code property available on KeyboardEvent events that will be the physical key pressed independent of the operating system keyboard layout.

This should make implementing custom keyboard shortcuts in your Electron app more accurate and consistent across machines and configurations.

window.addEventListener('keydown', function (event) {
console.log(`${event.code} was pressed.`);
});

Check out this example to see it in action.

Promise Rejection Events

Chrome 49 added two new window events that allow you to be notified when an rejected Promise goes unhandled.

window.addEventListener('unhandledrejection', function (event) {
console.log('A rejected promise was unhandled', event.promise, event.reason);
});

window.addEventListener('rejectionhandled', function (event) {
console.log('A rejected promise was handled', event.promise, event.reason);
});

Check out this example to see it in action.

ES2015 Updates in V8

The version of V8 now in Electron incorporates 91% of ES2015. Here are a few interesting additions you can use out of the box—without flags or pre-compilers:

Default parameters

function multiply(x, y = 1) {
return x * y;
}

multiply(5); // 5

Деструктирующее присваивание

Chrome 49 added destructuring assignment to make assigning variables and function parameters much easier.

This makes Electron requires cleaner and more compact to assign now:

Browser Process Requires
const { app, BrowserWindow, Menu } = require('electron');
Renderer Process Requires
const { dialog, Tray } = require('electron').remote;
Other Examples
// Destructuring an array and skipping the second element
const [first, , last] = findAll();

// Destructuring function parameters
function whois({ displayName: displayName, fullName: { firstName: name } }) {
console.log(`${displayName} is ${name}`);
}

let user = {
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe',
},
};
whois(user); // "jdoe is John"

// Destructuring an object
let { name, avatar } = getUser();

New Electron APIs

A few of the new Electron APIs are below, you can see each new API in the release notes for Electron releases.

show and hide events on BrowserWindow

These events are emitted when the window is either shown or hidden.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('show', function () {
console.log('Window was shown');
});
window.on('hide', function () {
console.log('Window was hidden');
});

platform-theme-changed on app for OS X

This event is emitted when the system’s Dark Mode theme is toggled.

const { app } = require('electron');

app.on('platform-theme-changed', function () {
console.log(`Platform theme changed. In dark mode? ${app.isDarkMode()}`);
});

app.isDarkMode() for OS X

This method returns true if the system is in Dark Mode, and false otherwise.

scroll-touch-begin and scroll-touch-end events to BrowserWindow for OS X

These events are emitted when the scroll wheel event phase has begun or has ended.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('scroll-touch-begin', function () {
console.log('Scroll touch started');
});
window.on('scroll-touch-end', function () {
console.log('Scroll touch ended');
});

API Changes Coming in Electron 1.0

· 4 мин. прочитано

Since the beginning of Electron, starting way back when it used to be called Atom-Shell, we have been experimenting with providing a nice cross-platform JavaScript API for Chromium's content module and native GUI components. The APIs started very organically, and over time we have made several changes to improve the initial designs.


Now with Electron gearing up for a 1.0 release, we'd like to take the opportunity for change by addressing the last niggling API details. The changes described below are included in 0.35.x, with the old APIs reporting deprecation warnings so you can get up to date for the future 1.0 release. An Electron 1.0 won't be out for a few months so you have some time before these changes become breaking.

Deprecation warnings

By default, warnings will show if you are using deprecated APIs. To turn them off you can set process.noDeprecation to true. To track the sources of deprecated API usages, you can set process.throwDeprecation to true to throw exceptions instead of printing warnings, or set process.traceDeprecation to true to print the traces of the deprecations.

New way of using built-in modules

Встроенные модули теперь сгруппированы в один модуль, а не разделены на независимые модули, так что вы можете использовать их без конфликтов с другими модулями:

var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;

The old way of require('app') is still supported for backward compatibility, but you can also turn if off:

require('electron').hideInternalModules();
require('app'); // throws error.

An easier way to use the remote module

Because of the way using built-in modules has changed, we have made it easier to use main-process-side modules in renderer process. You can now just access remote's attributes to use them:

// New way.
var app = require('electron').remote.app;
var BrowserWindow = require('electron').remote.BrowserWindow;

Instead of using a long require chain:

// Old way.
var app = require('electron').remote.require('app');
var BrowserWindow = require('electron').remote.require('BrowserWindow');

Splitting the ipc module

The ipc module existed on both the main process and renderer process and the API was different on each side, which is quite confusing for new users. We have renamed the module to ipcMain in the main process, and ipcRenderer in the renderer process to avoid confusion:

// В main процессе.
var ipcMain = require('electron').ipcMain;
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer;

And for the ipcRenderer module, an extra event object has been added when receiving messages, to match how messages are handled in ipcMain modules:

ipcRenderer.on('message', function (event) {
console.log(event);
});

Standardizing BrowserWindow options

The BrowserWindow options had different styles based on the options of other APIs, and were a bit hard to use in JavaScript because of the - in the names. They are now standardized to the traditional JavaScript names:

new BrowserWindow({ minWidth: 800, minHeight: 600 });

Following DOM's conventions for API names

The API names in Electron used to prefer camelCase for all API names, like Url to URL, but the DOM has its own conventions, and they prefer URL to Url, while using Id instead of ID. We have done the following API renames to match the DOM's styles:

  • Url is renamed to URL
  • Csp is renamed to CSP

You will notice lots of deprecations when using Electron v0.35.0 for your app because of these changes. An easy way to fix them is to replace all instances of Url with URL.

Changes to Tray's event names

The style of Tray event names was a bit different from other modules so a rename has been done to make it match the others.

  • clicked is renamed to click
  • double-clicked is renamed to double-click
  • right-clicked is renamed to right-click

Что нового в Electron

· 2 мин. прочитано

В последнее время были интересные обновления и разговоры про Electron, вот их сводка.


Источник

Electron теперь обновлен до версии Chrome 45 по состоянию на v0.32.0. Другие обновления включают...

Лучшая документация

new docs

Мы изменили структуру и стандартизировали документацию, с тем чтобы она лучше выглядела и лучше читалась. Существуют также переводы документации, внесенные общинами, такие, как японский и корейский.

Related pull requests: electron/electron#2028, electron/electron#2533, electron/electron#2557, electron/electron#2709, electron/electron#2725, electron/electron#2698, electron/electron#2649.

Node.js 4.1.0

Начиная с v0.33.0 Electron поставляется с Node.js 4.1.0.

Related pull request: electron/electron#2817.

node-pre-gyp

Теперь модули, основанные на node-pre-gyp, могут быть скомпилированы без Electron при сборке из исходного кода.

Related pull request: mapbox/node-pre-gyp#175.

Поддержка ARM

Electron теперь предоставляет сборки для Linux на ARMv7. Он работает на популярных платформах, таких как Chromebook и Raspberry Pi 2.

Связанные вопросы: atom/libchromiumcontent#138, electron/electron#2094, electron/electron#366.

Безрамное окно в стиле Yosemite

безрамное окно

A patch by @jaanus has been merged that, like the other built-in OS X apps, allows creating frameless windows with system traffic lights integrated on OS X Yosemite and later.

Related pull request: electron/electron#2776.

Google Summer of Code Printing Support

После Google Summer of Code мы объединили патчи на [@hokein](https://github. com/hokein), чтобы улучшить поддержку печати, и добавили возможность печати страницы в PDF файлы.

Связанные вопросы: Электрон/электрон#2677, электрон/электрон#1935, электрон/электрон#1532, electron/electron#805, electron/electron#1669, electron/electron#1835.

Atom

Atom обновлен до v0.30.6 с Chrome 44. Идет обновление до v0.33.0 на atom/atom#8779.

Talks

GitHubber Amy Palamountain gave a great introduction to Electron in a talk at Nordic.js. She also created the electron-accelerator library.

Создание нативных приложений с Electron от Amy Palomountain

Ben Ogle, also on the Atom team, gave an Electron talk at YAPC Asia:

Building Desktop Apps with Web Technologies by Ben Ogle

Atom team member Kevin Sawicki and others gave talks on Electron at the Bay Are Electron User Group meetup recently. видео были опубликованы этими людьми:

История Electron от Кевина Савицки

Заставить веб-приложение чувствовать себя нативными благодаря Бен Гооу