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

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!

Простое автообновление приложений с открытым исходным кодом

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

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


Новый модуль обновления в действии

Делаем жизнь проще

В Electron есть API autoUpdater, который дает приложениям возможность использовать метаданные из удалённой конечной точки, чтобы проверять наличие обновлений, скачивать их в фоновом режиме и автоматически устанавливать их.

Enabling these updates has been a cumbersome step in the deployment process for many Electron app developers because it requires a web server to be deployed and maintained just to serve app version history metadata.

Сегодня мы анонсируем новое решение для автоматического обновления приложений. Если ваше приложение Electron находится в публичном репозитории GitHub и вы используете GitHub Releases для публикации сборок, вы можете использовать этот сервис для непрерывной доставки обновлений приложения своим пользователям.

Использование нового модуля

Чтобы свести к минимуму настройки с вашей стороны, мы создали update-electron-app, модуль npm, который интегрируется с новым веб-сервисом update.electronjs.org.

Установить модуль:

npm install update-electron-app

Вызовите его из любого места в главном процессе вашего приложения:

require('update-electron-app')();

Вот и всё! Модуль будет проверять наличие обновлений при запуске приложения, а затем каждые десять минут. При обнаружении обновления, оно будет скачано автоматически в фоновом режиме, когда обновление завершится, появится диалоговое окно.

Перенос существующих приложений

Приложения, уже использующие autoUpdater API Electron, также могут использовать эту службу. Для этого вы можете настроить модуль update-electron-app или интегрировать его напрямую с update.electronjs.org.

Альтернативы

Если вы используете electron-builder для упаковки своего приложения, то можно использовать его встроенный инструмент обновления. Подробности смотрите в electron.build/auto-update.

Если ваше приложение является приватным, то может потребоваться запустить собственный сервер обновлений. Для этого существует ряд инструментов с открытым исходным кодом, в том числе Hazel компании Zeit и Nucleus компании Atlassian. Дополнительные сведения смотрите в руководстве Развертывание сервера обновлений.

Thanks

Благодарим Julian Gruber за помощь в разработке и создании этого простого и масштабируемого веб-сервиса. Благодарим ребят из Zeit за сервис Hazel с открытым исходным кодом, из которого мы черпали вдохновение для дизайна. Благодарим Samuel Attard за рецензии кода. Благодарим сообщество Electron за помощь в тестировании этого сервиса.

🌲 За вечнозеленое будущее приложений Electron!

New in Electron 2: In-App Purchases

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

The new Electron 2.0 release line is packed with new features and fixes. One of the highlights from this new major version is a new inAppPurchase API for Apple's Mac App Store.


In-app purchases enable content or subscriptions to be purchased directly from within apps. This gives developers an easy way to embrace the freemium business model, wherein users pay nothing to download an app and are offered optional in-app purchases for premium features, additional content, or subscriptions.

The new API was added to Electron by community contributor Adrien Fery to enable in-app purchases in Amanote, a note-taking Electron app for lectures and conferences. Amanote is free to download and allows clear and structured notes to be added to PDFs, with features like mathematical formulae, drawings, audio recording, and more.

Since adding in-app purchase support to the Mac version of Amanote, Adrien has noted a 40% increase in sales!

Начало работы

The new inAppPurchase API has already landed in the latest Electron beta:

npm i -D electron@beta

The docs for the API can be found on GitHub, and Adrien has been kind enough to write a tutorial on how to use the API. To get started adding in-app purchases to your app, see the tutorial.

More improvements to the API are in the works, and will soon be landing in an upcoming Electron beta release.

Windows Could Be Next

Up next, Adrien is hoping to open a new revenue channel for Amanote by adding support for Microsoft Store in-app purchases in Electron. Stay tuned for developments on that!

Webview Vulnerability Fix

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

A vulnerability has been discovered which allows Node.js integration to be re-enabled in some Electron applications that disable it. This vulnerability has been assigned the CVE identifier CVE-2018-1000136.


Affected Applications

An application is affected if all of the following are true:

  1. Runs on Electron 1.7, 1.8, or a 2.0.0-beta
  2. Allows execution of arbitrary remote code
  3. Disables Node.js integration
  4. Does not explicitly declare webviewTag: false in its webPreferences
  5. Does not enable the nativeWindowOption option
  6. Does not intercept new-window events and manually override event.newGuest without using the supplied options tag

Although this appears to be a minority of Electron applicatons, we encourage all applications to be upgraded as a precaution.

Mitigation

This vulnerability is fixed in today's 1.7.13, 1.8.4, and 2.0.0-beta.5 releases.

Developers who are unable to upgrade their application's Electron version can mitigate the vulnerability with the following code:

app.on('web-contents-created', (event, win) => {
win.on(
'new-window',
(event, newURL, frameName, disposition, options, additionalFeatures) => {
if (!options.webPreferences) options.webPreferences = {};
options.webPreferences.nodeIntegration = false;
options.webPreferences.nodeIntegrationInWorker = false;
options.webPreferences.webviewTag = false;
delete options.webPreferences.preload;
}
);
});

// and *IF* you don't use WebViews at all,
// you might also want
app.on('web-contents-created', (event, win) => {
win.on('will-attach-webview', (event, webPreferences, params) => {
event.preventDefault();
});
});

Further Information

This vulnerability was found and reported responsibly to the Electron project by Brendan Scarvell of Trustwave SpiderLabs.

To learn more about best practices for keeping your Electron apps secure, see our security tutorial.

To report a vulnerability in Electron, please email security@electronjs.org.

Please join our email list to receive updates about releases and security updates.

Website Hiccups

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

Last week the electronjs.org site had a few minutes of downtime. If you were affected by these brief outages, we're sorry for the inconvenience. After a bit of investigation today, we've diagnosed the root cause and have deployed a fix.


To prevent this kind of downtime in the future, we've enabled Heroku threshold alerts on our app. Any time our web server accumulates failed requests or slow responses beyond a certain threshold, our team will be notified so we can address the problem quickly.

Offline Docs in Every Language

The next time you're developing an Electron app on a plane or in a subterranean coffee shop, you might want to have a copy of the docs for offline reference. Fortunately, Electron's docs are available as Markdown files in over 20 languages.

git clone https://github.com/electron/electron-i18n
ls electron-i18n/content

Offline Docs with a GUI

devdocs.io/electron is a handy website that stores docs for offline use, not just for Electron but many other projects like JavaScript, TypeScript, Node.js, React, Angular, and many others. And of course there's an Electron app for that, too. Check out devdocs-app on the Electron site.

devdocs-app

If you like to install apps without using your mouse or trackpad, give Electron Forge's install command a try:

npx electron-forge install egoist/devdocs-app

Protocol Handler Vulnerability Fix

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

A remote code execution vulnerability has been discovered affecting Electron apps that use custom protocol handlers. This vulnerability has been assigned the CVE identifier CVE-2018-1000006.


Affected Platforms

Electron apps designed to run on Windows that register themselves as the default handler for a protocol, like myapp://, are vulnerable.

Such apps can be affected regardless of how the protocol is registered, e.g. using native code, the Windows registry, or Electron's app.setAsDefaultProtocolClient API.

macOS and Linux are not vulnerable to this issue.

Mitigation

We've published new versions of Electron which include fixes for this vulnerability: 1.8.2-beta.5, 1.7.12, and 1.6.17. We urge all Electron developers to update their apps to the latest stable version immediately.

Если по какой-то причине вы не можете обновить версию Electron, вы можете добавить -- в качестве последнего аргумента при вызове приложения . etAsDefaultProtocolClient, , который не позволяет Chromium анализировать дальнейшие параметры. The double dash -- signifies the end of command options, after which only positional parameters are accepted.

app.setAsDefaultProtocolClient(protocol, process.execPath, [
'--your-switches-here',
'--',
]);

Смотрите app.setAsfaultProtocolClient API для получения более подробной информации.

Чтобы узнать больше о лучших методах обеспечения безопасности приложений Electron, смотрите наш учебник по безопасности.

If you wish to report a vulnerability in Electron, email security@electronjs.org.

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's New Internationalized Website

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

Electron has a new website at electronjs.org! We've replaced our static Jekyll site with a Node.js webserver, giving us flexibility to internationalize the site and paving the way for more exciting new features.


🌍 Translations

We've begun the process of internationalizing the website with the goal of making Electron app development accessible to a global audience of developers. We're using a localization platform called Crowdin that integrates with GitHub, opening and updating pull requests automatically as content is translated into different languages.

Electron Nav in Simplified Chinese

Though we've been working quietly on this effort so far, over 75 Electron community members have already discovered the project organically and joined in the effort to internationalize the website and translate Electron's docs into over 20 languages. We are seeing daily contributions from people all over the world, with translations for languages like French, Vietnamese, Indonesian, and Chinese leading the way.

To choose your language and view translation progress, visit electronjs.org/languages

Translations in progress on Crowdin

If you're multilingual and interested in helping translate Electron's docs and website, visit the electron/electron-i18n repo, or jump right into translating on Crowdin, where you can sign in using your GitHub account.

There are currently 21 languages enabled for the Electron project on Crowdin. Adding support for more languages is easy, so if you're interested in helping translate but you don't see your language listed, let us know and we'll enable it.

Raw Translated Docs

If you prefer to read documentation in raw markdown files, you can now do that in any language:

git clone https://github.com/electron/electron-i18n
ls electron-i18n/content

App Pages

As of today, any Electron app can easily have its own page on the Electron site. For a few examples, check out Etcher, 1Clipboard, or GraphQL Playground, pictured here on the Japanese version of the site:

GraphQL Playground

There are some incredible Electron apps out there, but they're not always easy to find, and not every developer has the time or resources to build a proper website to market and distribute their app.

Using just a PNG icon file and a small amount of app metadata, we're able to collect a lot of information about a given app. Using data collected from GitHub, app pages can now display screenshots, download links, versions, release notes, and READMEs for every app that has a public repository. Using a color palette extracted from each app's icon, we can produce bold and accessible colors to give each app page some visual distinction.

The apps index page now also has categories and a keyword filter to find interesting apps like GraphQL GUIs and p2p tools.

If you've got an Electron app that you'd like featured on the site, open a pull request on the electron/electron-apps repository.

One-line Installation with Homebrew

The Homebrew package manager for macOS has a subcommand called cask that makes it easy to install desktop apps using a single command in your terminal, like brew cask install atom.

We've begun collecting Homebrew cask names for popular Electron apps and are now displaying the installation command (for macOS visitors) on every app page that has a cask:

Installation options tailored for your platform: macOS, Windows, Linux

To view all the apps that have homebrew cask names, visit electronjs.org/apps?q=homebrew. If you know of other apps with casks that we haven't indexed yet, please add them!

🌐 A New Domain

We've moved the site from electron.atom.io to a new domain: electronjs.org.

The Electron project was born inside Atom, GitHub's open-source text editor built on web technologies. Electron was originally called atom-shell. Atom was the first app to use it, but it didn't take long for folks to realize that this magical Chromium + Node runtime could be used for all kinds of different applications. When companies like Microsoft and Slack started to make use of atom-shell, it became clear that the project needed a new name.

And so "Electron" was born. In early 2016, GitHub assembled a new team to focus specifically on Electron development and maintenance, apart from Atom. In the time since, Electron has been adopted by thousands of app developers, and is now depended on by many large companies, many of which have Electron teams of their own.

Supporting GitHub's Electron projects like Atom and GitHub Desktop is still a priority for our team, but by moving to a new domain we hope to help clarify the technical distinction between Atom and Electron.

🐢🚀 Node.js Everywhere

The previous Electron website was built with Jekyll, the popular Ruby-based static site generator. Jekyll is a great tool for building static websites, but the website had started to outgrow it. We wanted more dynamic capabilities like proper redirects and dynamic content rendering, so a Node.js server was the obvious choice.

The Electron ecosystem includes projects with components written in many different programming languages, from Python to C++ to Bash. But JavaScript is foundational to Electron, and it's the language used most in our community.

By migrating the website from Ruby to Node.js, we aim to lower the barrier to entry for people wishing to contribute to the website.

⚡️ Easier Open-Source Participation

If you've got Node.js (8 or higher) and git installed on your system, you can easily get the site running locally:

git clone https://github.com/electron/electronjs.org
cd electronjs.org
npm install
npm run dev

The new website is hosted on Heroku. We use deployment pipelines and the Review Apps feature, which automatically creates a running copy of the app for every pull request. This makes it easy for reviewers to view the actual effects of a pull request on a live copy of the site.

🙏 Thanks to Contributors

We'd like to give special thanks to all the folks around the world who have contributed their own time and energy to help improve Electron. The passion of the open-source community has helped immeasurably in making Electron a success. Thank you!

Thumbs up!

Исправление уязвимости RCE в Chromium

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

В Google Chromium обнаружена уязвимость удаленного выполнения кода, это влияет на все последние версии Electron. Любое приложение Electron, имеющее доступ к удаленному контенту, уязвимо к этому эксплойту, независимо от того, включена ли опция "песочница "".

Мы опубликовали две новые версии Electron 1.7.8 и 1.6.14, оба из которых включают исправление для этой уязвимости. Мы призываем всех Electron разработчикам немедленно обновить свои приложения до последней стабильной версии:

npm i electron@latest --save-dev

Чтобы узнать больше о лучших методах обеспечения безопасности приложений Electron, смотрите наш учебник по безопасности.

Пожалуйста, свяжитесь с security@electronjs.org, если вы хотите сообщить об уязвимости в Electron.

Announcing TypeScript support in Electron

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

electron npm package теперь включает в себя файл определения TypeScript, который содержит подробные аннотации всего Electron API. These annotations can improve your Electron development experience even if you're writing vanilla JavaScript. Just npm install electron to get up-to-date Electron typings in your project.


TypeScript is an open-source programming language created by Microsoft. It's a superset of JavaScript that extends the language by adding support for static types. The TypeScript community has grown quickly in recent years, and TypeScript was ranked among the most loved programming languages in a recent Stack Overflow developer survey. TypeScript is described as "JavaScript that scales", and teams at GitHub, Slack, and Microsoft are all using it to write scalable Electron apps that are used by millions of people.

TypeScript supports many of the newer language features in JavaScript like classes, object destructuring, and async/await, but its real differentiating feature is type annotations. Объявление типов входных и выходных данных, ожидаемых вашей программой, может уменьшить количество ошибок, помогая вам находить ошибки во время компиляции, а аннотации могут также служить формальным заявлением о том, как ваша программа работает.

When libraries are written in vanilla Javascript, the types are often vaguely defined as an afterthought when writing documentation. Functions can often accept more types than what was documented, or a function can have invisible constraints that are not documented, which can lead to runtime errors.

TypeScript solves this problem with definition files. A TypeScript definition file describes all the functions of a library and its expected input and output types. When library authors bundle a TypeScript definition file with their published library, consumers of that library can explore its API right inside their editor and start using it right away, often without needing to consult the library's documentation.

Many popular projects like Angular, Vue.js, node-github (and now Electron!) compile their own definition file and bundle it with their published npm package. For projects that don't bundle their own definition file, there is DefinitelyTyped, a third-party ecosystem of community-maintained definition files.

Установка

Starting at version 1.6.10, every release of Electron includes its own TypeScript definition file. When you install the electron package from npm, the electron.d.ts file is bundled automatically with the installed package.

The safest way to install Electron is using an exact version number:

npm install electron --save-dev --save-exact

Or if you're using yarn:

yarn add electron --dev --exact

If you were already using third-party definitions like @types/electron and @types/node, you should remove them from your Electron project to prevent any collisions.

The definition file is derived from our structured API documentation, so it will always be consistent with Electron's API documentation. Just install electron and you'll always get TypeScript definitions that are up to date with the version of Electron you're using.

Usage

For a summary of how to install and use Electron's new TypeScript annotations, watch this short demo screencast:

If you're using Visual Studio Code, you've already got TypeScript support built in. There are also community-maintained plugins for Atom, Sublime, vim, and other editors.

Once your editor is configured for TypeScript, you'll start to see more context-aware behavior like autocomplete suggestions, inline method reference, argument checking, and more.

Method autocompletion

Method reference

Argument checking

Getting started with TypeScript

If you're new to TypeScript and want to learn more, this introductory video from Microsoft provides a nice overview of why the language was created, how it works, how to use it, and where it's headed.

There's also a handbook and a playground on the official TypeScript website.

Because TypeScript is a superset of JavaScript, your existing JavaScript code is already valid TypeScript. This means you can gradually transition an existing JavaScript project to TypeScript, sprinkling in new language features as needed.

Thanks

This project would not have been possible without the help of Electron's community of open-source maintainers. Thanks to Samuel Attard, Felix Rieseberg, Birunthan Mohanathas, Milan Burda, Brendan Forster, and many others for their bug fixes, documentation improvements, and technical guidance.

Поддержка

If you encounter any issues using Electron's new TypeScript definition files, please file an issue on the electron-typescript-definitions repository.

Happy TypeScripting!