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

Специальные возможности

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

Создание доступных приложений важно и мы рады представить новые функции Devtron и Spectron, что дает разработчикам возможность делать свои приложения лучше для всех.


Проблемы с доступностью в приложениях Electron аналогичны веб-сайтам, поскольку они оба в конечном итоге являются HTML. Однако в приложениях Electron вы не можете использовать онлайн-ресурсы для аудита доступности, потому что ваше приложение не имеет URL-адреса, чтобы указать аудитору.

Эти новые функции приносят эти инструменты аудита в ваше приложение Electron. Эти новые возможности приносят эти инструменты аудита в ваше приложение Electron. Прочитайте сводки инструментов или проверки нашей доступной документации для получения дополнительной информации.

Spectron

В тестовом фреймворке Spectron, вы можете совершить аудит каждого окна и <webview> в вашем приложении. Например:

app.client.auditAccessibility().then(function (audit) {
if (audit.failed) {
console.error(audit.message);
}
});

Вы можете прочитать больше об этой функции в Spectron документации.

Devtron

В Devtron есть новая вкладка доступности, которая позволит вам совершить аудит страницы в вашем приложении, сортировать и фильтровать результаты.

devtron скриншот

Оба эти средства используют Accessibility Developer Tools библиотеки, построенных для Google Chrome. Вы можете узнать больше о доступности правила аудита, которые эта библиотека использует в этих репозиториях wiki.

Если вы знаете другие инструменты доступности для Electron, добавьте их к accessibility documentation pull request'том.

npm install electron

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

Начиная с версии Electron 1.3.1, вы можете выполнить npm install electron --save-dev для установки последней скомпилированной версии Electron в ваше приложение.


npm install electron

The prebuilt Electron binary

If you've ever worked on an Electron app before, you've likely come across the electron-prebuilt npm package. This package is an indispensable part of nearly every Electron project. When installed, it detects your operating system and downloads a prebuilt binary that is compiled to work on your system's architecture.

The new name

The Electron installation process was often a stumbling block for new developers. Many brave people tried to get started developing an Electron by app by running npm install electron instead of npm install electron-prebuilt, only to discover (often after much confusion) that it was not the electron they were looking for.

This was because there was an existing electron project on npm, created before GitHub's Electron project existed. To help make Electron development easier and more intuitive for new developers, we reached out to the owner of the existing electron npm package to ask if he'd be willing to let us use the name. Luckily he was a fan of our project, and agreed to help us repurpose the name.

Prebuilt lives on

As of version 1.3.1, we have begun publishing electron and electron-prebuilt packages to npm in tandem. The two packages are identical. We chose to continue publishing the package under both names for a while so as not to inconvenience the thousands of developers who are currently using electron-prebuilt in their projects. We recommend updating your package.json files to use the new electron dependency, but we will continue releasing new versions of electron-prebuilt until the end of 2016.

The electron-userland/electron-prebuilt repository will remain the canonical home of the electron npm package.

Many thanks

We owe a special thanks to @mafintosh, @maxogden, and many other contributors for creating and maintaining electron-prebuilt, and for their tireless service to the JavaScript, Node.js, and Electron communities.

And thanks to @logicalparadox for allowing us to take over the electron package on npm.

Updating your projects

We've worked with the community to update popular packages that are affected by this change. Packages like electron-packager, electron-rebuild, and electron-builder have already been updated to work with the new name while continuing to support the old name.

If you encounter any problems installing this new package, please let us know by opening an issue on the electron-userland/electron-prebuilt repository.

For any other issues with Electron, please use the electron/electron repository.

Electron Internals: Using Node as a Library

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

This is the second post in an ongoing series explaining the internals of Electron. Посмотрите первый пост о интеграции цикла событий , если вы еще этого не сделали.

Most people use Node for server-side applications, but because of Node's rich API set and thriving community, it is also a great fit for an embedded library. This post explains how Node is used as a library in Electron.


Build system

Узел и Electron используют GYP в качестве их систем сборки. If you want to embed Node inside your app, you have to use it as your build system too.

New to GYP? Прочтите это руководство прежде чем вы продолжите работу в этом сообщении.

Node's flags

узел. yp файл в директории исходного кода узла описывает, как строится узел , вместе со множеством переменных GYP управляет какими частями узла и открывают ли некоторые конфигурации.

To change the build flags, you need to set the variables in the .gypi file of your project. The configure script in Node can generate some common configurations for you, for example running ./configure --shared will generate a config.gypi with variables instructing Node to be built as a shared library.

Electron does not use the configure script since it has its own build scripts. Конфигурации для узла определены в файле common.gypi в корневом каталоге исходного кода Electron.

In Electron, Node is being linked as a shared library by setting the GYP variable node_shared to true, so Node's build type will be changed from executable to shared_library, and the source code containing the Node's main entry point will not be compiled.

Since Electron uses the V8 library shipped with Chromium, the V8 library included in Node's source code is not used. This is done by setting both node_use_v8_platform and node_use_bundled_v8 to false.

Shared library or static library

When linking with Node, there are two options: you can either build Node as a static library and include it in the final executable, or you can build it as a shared library and ship it alongside the final executable.

In Electron, Node was built as a static library for a long time. This made the build simple, enabled the best compiler optimizations, and allowed Electron to be distributed without an extra node.dll file.

Тем не менее, это изменилось после того, как Chrome переключился на использование BoringSSL. BoringSSL — это ответвление OpenSSL , которое удаляет несколько неиспользуемых API и изменяет многие существующие интерфейсы. Because Node still uses OpenSSL, the compiler would generate numerous linking errors due to conflicting symbols if they were linked together.

Electron не смог использовать BoringSSL в узле или использовать OpenSSL в Chromium, чтобы единственный вариант заключался в том, чтобы переключиться на построение узла в качестве разделяемой библиотеки, и скрыть символы BoringSSL и OpenSSL в компонентах каждого из них.

This change brought Electron some positive side effects. Before this change, you could not rename the executable file of Electron on Windows if you used native modules because the name of the executable was hard coded in the import library. After Node was built as a shared library, this limitation was gone because all native modules were linked to node.dll, whose name didn't need to be changed.

Supporting native modules

Нативные модули в работе узла определяют функцию ввода для загрузки узла, и затем поиск символов V8 и libuv из узла. This is a bit troublesome for embedders because by default the symbols of V8 and libuv are hidden when building Node as a library and native modules will fail to load because they cannot find the symbols.

So in order to make native modules work, the V8 and libuv symbols were exposed in Electron. For V8 this is done by forcing all symbols in Chromium's configuration file to be exposed. For libuv, it is achieved by setting the BUILDING_UV_SHARED=1 definition.

Starting Node in your app

After all the work of building and linking with Node, the final step is to run Node in your app.

Node doesn't provide many public APIs for embedding itself into other apps. Обычно вы можете просто вызвать узел::Start и узел::Init , чтобы запустить новый экземпляр узла. However, if you are building a complex app based on Node, you have to use APIs like node::CreateEnvironment to precisely control every step.

In Electron, Node is started in two modes: the standalone mode that runs in the main process, which is similar to official Node binaries, and the embedded mode which inserts Node APIs into web pages. The details of this will be explained in a future post.

July 2016: New Apps and Meetups

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

We're starting a monthly roundup to highlight activity in the Electron community. Each roundup will feature things like new apps, upcoming meetups, tools, videos, etc.


This site is updated with new apps and meetups through pull requests from the community. You can watch the repository to get notifications of new additions or if you're not interested in all of the site's changes, subscribe to the blog RSS feed.

If you've made an Electron app or host a meetup, make a pull request to add it to the site and it will make the next roundup.

New Apps

DemioA Webinar platform built for inbound sales and marketing
ElectorrentA remote client app for uTorrent server
PhoneGapThe open source framework that gets you building amazing mobile apps using web technology
WordMarkA lightweight blog publishing editor for Markdown writers
UbAuthApp to help developers create access tokens for Uber applications with OAuth 2.0
HyperTermHTML/JS/CSS terminal
MarpMarkdown presentation writer
Glyphr StudioA free, web based font designer, focusing on font design for hobbyists
BitCryptA simple file encryption application for Windows Encrypt your bits
TrymBeautiful small app for macOS to help you view, optimize and convert SVG icons
BookerText editor with the power of Markdown
PhonePresenterThe smartest presentation clicker
YoutThe new way to watch your playlists from YouTube on desktop

New Meetups

Electron Open Source Desktop FrameworkLondon, UK

Electron Internals: Message Loop Integration

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

This is the first post of a series that explains the internals of Electron. This post introduces how Node's event loop is integrated with Chromium in Electron.


Было сделано много попыток использовать узел для программирования GUI, как node-gui для привязки GTK+ и node-qt для привязки QT. But none of them work in production because GUI toolkits have their own message loops while Node uses libuv for its own event loop, and the main thread can only run one loop at the same time. So the common trick to run GUI message loop in Node is to pump the message loop in a timer with very small interval, which makes GUI interface response slow and occupies lots of CPU resources.

During the development of Electron we met the same problem, though in a reversed way: we had to integrate Node's event loop into Chromium's message loop.

The main process and renderer process

Before we dive into the details of message loop integration, I'll first explain the multi-process architecture of Chromium.

В Electron есть два типа процессов: главный процесс и процесс обработчика (это на самом деле чрезвычайно упрощено, полностью, см. Многопроцессорная архитектура). The main process is responsible for GUI work like creating windows, while the renderer process only deals with running and rendering web pages.

Electron allows using JavaScript to control both the main process and renderer process, which means we have to integrate Node into both processes.

Replacing Chromium's message loop with libuv

My first try was reimplementing Chromium's message loop with libuv.

It was easy for the renderer process, since its message loop only listened to file descriptors and timers, and I only needed to implement the interface with libuv.

However it was significantly more difficult for the main process. Each platform has its own kind of GUI message loops. macOS Chromium uses NSRunLoop, whereas Linux uses glib. I tried lots of hacks to extract the underlying file descriptors out of the native GUI message loops, and then fed them to libuv for iteration, but I still met edge cases that did not work.

So finally I added a timer to poll the GUI message loop in a small interval. As a result the process took a constant CPU usage, and certain operations had long delays.

Polling Node's event loop in a separate thread

As libuv matured, it was then possible to take another approach.

The concept of backend fd was introduced into libuv, which is a file descriptor (or handle) that libuv polls for its event loop. So by polling the backend fd it is possible to get notified when there is a new event in libuv.

So in Electron I created a separate thread to poll the backend fd, and since I was using the system calls for polling instead of libuv APIs, it was thread safe. And whenever there was a new event in libuv's event loop, a message would be posted to Chromium's message loop, and the events of libuv would then be processed in the main thread.

In this way I avoided patching Chromium and Node, and the same code was used in both the main and renderer processes.

The code

Вы можете найти реализацию интеграции цикла сообщений в node_bindings файлах в electron/atom/common/. It can be easily reused for projects that want to integrate Node.

Update: Implementation moved to electron/shell/common/node_bindings.cc.

Electron Podcasts

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

Looking for an introduction to Electron? Two new podcasts have just been released that give a great overview of what it is, why it was built, and how it is being used.


Out now:

Hanselminutes: Creating cross-platform Electron apps

Is Electron "just Chrome in a frame" or is it so much more? Jessica sets Scott on the right path and explains exactly where the Electron platform fits into your development world.


JavaScript Air: Electron Apps

Electron is becoming more and more of a relevant and popular way of building multi-platform desktop apps with web technologies. Let's get a dive into this awesome tech and see how we can use it to enhance our own experience and our user's experience on the desktop.


If you're looking for an introduction to Electron, give the first a listen. The second goes into more detail about building apps with great tips from Nylas's Evan Morikawa.

We are currently working on two more podcasts that should come out next month, keep an eye on the @ElectronJS Twitter account for updates.

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 на вкладке Styles

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();

Новые API Electron

Ниже приведены некоторые из новых API Electron, а также вы можете ознакомиться с каждым новым API в примечаниях к релизам Electron releases.

События show и hide для BrowserWindow

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

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

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('show', function () {
console.log('Окно было отображено');
});
window.on('hide', function () {
console.log('Окно было скрыто');
});

platform-theme-changed на app для OS X

Это событие возникает, когда переключается системная тема Dark Mode.

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

app.on('platform-theme-changed', function () {
console.log(`Тема платформы изменена. Тёмный режим? ${app.isDarkMode()}`);
});

app.isDarkMode() для OS X

Этот метод возвращает true, если система находится в темном режиме, и false в противном случае.

События scroll-touch-begin и scroll-touch-end в BrowserWindow для OS X

Эти события возникают, когда начинается или заканчивается фаза событий при прокрутке.

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

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('scroll-touch-begin', function () {
console.log('Прокрутка касанием началась');
});
window.on('scroll-touch-end', function () {
console.log(''Прокрутка касанием закончилась'');
});

Use V8 and Chromium Features in Electron

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

Building an Electron application means you only need to create one codebase and design for one browser, which is pretty handy. But because Electron stays up to date with Node.js and Chromium as they release, you also get to make use of the great features they ship with. In some cases this eliminates dependencies you might have previously needed to include in a web app.


There are many features and we'll cover some here as examples, but if you're interested in learning about all features you can keep an eye on the Google Chromium blog and Node.js changelogs. You can see what versions of Node.js, Chromium and V8 Electron is using at electronjs.org/#electron-versions.

ES6 Support through V8

Electron combines Chromium's rendering library with Node.js. The two share the same JavaScript engine, V8. Many ECMAScript 2015 (ES6) features are already built into V8 which means you can use them in your Electron application without any compilers.

Below are a few examples but you can also get classes (in strict mode), block scoping, promises, typed arrays and more. Check out this list for more information on ES6 features in V8.

Arrow Functions

findTime () => {
console.log(new Date())
}

String Interpolation

var octocat = 'Mona Lisa';
console.log(`The octocat's name is ${octocat}`);

New Target

Octocat() => {
if (!new.target) throw "Not new";
console.log("New Octocat");
}

// Throws
Octocat();
// Logs
new Octocat();

Array Includes

// Returns true
[1, 2].includes(2);

Rest Parameters

// Represent indefinite number of arguments as an array
(o, c, ...args) => {
console.log(args.length);
};

Chromium Features

Thanks to all the hard work Google and contributors put into Chromium, when you build Electron apps you can also use cool things like (but not limited to):

Follow along with the Google Chromium blog to learn about features as new versions ship and again, you can check the version of Chromium that Electron uses here.

What are you excited about?

Tweet to us @ElectronJS with your favorite features built into V8 or Chromium.

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