Saltar al contenido principal

From native to JavaScript in Electron

· 3 lectura mínima

How do Electron's features written in C++ or Objective-C get to JavaScript so they're available to an end-user?


Fondo

Electron is a JavaScript platform whose primary purpose is to lower the barrier to entry for developers to build robust desktop apps without worrying about platform-specific implementations. However, at its core, Electron itself still needs platform-specific functionality to be written in a given system language.

In reality, Electron handles the native code for you so that you can focus on a single JavaScript API.

How does that work, though? How do Electron's features written in C++ or Objective-C get to JavaScript so they're available to an end-user?

To trace this pathway, let's start with the app module.

By opening the app.ts file inside our lib/ directory, you'll find the following line of code towards the top:

const binding = process.electronBinding('app');

This line points directly to Electron's mechanism for binding its C++/Objective-C modules to JavaScript for use by developers. Desbloqueo.ElectronBindings``ElectronBindings

process.electronBinding

These files add the process.electronBinding function, which behaves like Node.js’ process.binding. process.binding is a lower-level implementation of Node.js' require() method, except it allows users to require native code instead of other code written in JS. This custom process.electronBinding function confers the ability to load native code from Electron.

When a top-level JavaScript module (like app) requires this native code, how is the state of that native code determined and set? Where are the methods exposed up to JavaScript? What about the properties?

native_mate

At present, answers to this question can be found in native_mate: a fork of Chromium's gin library that makes it easier to marshal types between C++ and JavaScript.

Inside native_mate/native_mate there's a header and implementation file for object_template_builder.

mate::ObjectTemplateBuilder

If we look at every Electron module as an object, it becomes easier to see why we would want to use object_template_builder to construct them. This class is built on top of a class exposed by V8, which is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. V8 implements the JavaScript (ECMAScript) specification, so its native functionality implementations can be directly correlated to implementations in JavaScript. For example, v8::ObjectTemplate gives us JavaScript objects without a dedicated constructor function and prototype. It uses Object[.prototype], and in JavaScript would be equivalent to Object.create().

To see this in action, look to the implementation file for the app module, atom_api_app.cc. At the bottom is the following:

mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("getGPUInfo", &App::GetGPUInfo)

In the above line, .SetMethod is called on mate::ObjectTemplateBuilder. .SetMethod can be called on any instance of the ObjectTemplateBuilder class to set methods on the Object prototype in JavaScript, with the following syntax:

.SetMethod("method_name", &function_to_bind)

This is the JavaScript equivalent of:

function App{}
App.prototype.getGPUInfo = function () {
// implementation here
}

This class also contains functions to set properties on a module:

.SetProperty("property_name", &getter_function_to_bind)

o

.SetProperty("property_name", &getter_function_to_bind, &setter_function_to_bind)

These would in turn be the JavaScript implementations of Object.defineProperty:

function App {}
Object.defineProperty(App.prototype, 'myProperty', {
get() {
return _myProperty
}
})

y

function App {}
Object.defineProperty(App.prototype, 'myProperty', {
get() {
return _myProperty
}
set(newPropertyValue) {
_myProperty = newPropertyValue
}
})

It’s possible to create JavaScript objects formed with prototypes and properties as developers expect them, and more clearly reason about functions and properties implemented at this lower system level!

The decision around where to implement any given module method is itself a complex and oft-nondeterministic one, which we'll cover in a future post.

Gobernanza Electron

· 2 lectura mínima

As Electron grows in popularity for desktop applications, the team working on it has also grown: we have more fulltime maintainers who work for different companies, live in different timezones, and have different interests. We're introducing a governance structure so we can keep growing smoothly.


Why are things changing?

People in the Electron project coordinate in timezones around the world with volunteers, with full-time maintainers, and with several companies who all rely on Electron. Until now, we've been successful with informal coordination; but as the team has grown, we've found that the approach doesn't scale. We also want to make it easier for new contributors to find a place to call home in the project.

Grupos de trabajo

Electron governance includes working groups that are responsible for different parts of the project. We're starting out with seven groups:

  • Community & Safety: Handles Code of Conduct issues.
  • Docs & Tooling: Oversees externally-focused tooling (e.g. Fiddle, Forge) and the Electron documentation.
  • Outreach: Helps grow the Electron community.
  • Releases: Ensures releases are stable and on schedule.
  • Security: Performs security testing and responds to security issues.
  • Upgrades: Integrates upstream upgrades, such as new versions of V8, Chromium, and Node.
  • Website: Maintains and improves the Electron website.

These groups will coordinate with each other, but each has their own meeting schedules and agendas to be productive on their own. More details on these groups are available at the governance repository.

Does this change the Electron project's direction?

This shouldn't have any direct effect on Electron's direction. If our strategy is successful, working groups will make it easier for new contributors to find topics that interest them, and make maintainers' lives simpler by moving discussion unrelated to their day-to-day work to other groups. If that happens, it may indirectly affect things by having more unblocked people working together.

Where can I learn more?

Chromium FileReader Vulnerability Fix

· Lectura de un minuto

A High severity vulnerability has been discovered in Chrome which affects all software based on Chromium, including Electron.

This vulnerability has been assigned CVE-2019-5786. You can read more about it in the Chrome Blog Post.

Please note that Chrome has reports of this vulnerability being used in the wild so it is strongly recommended you upgrade Electron ASAP.


Ámbito

This affects any Electron application that may run third-party or untrusted JavaScript.

Mitigación

Affected apps should upgrade to a patched version of Electron.

We've published new versions of Electron which include fixes for this vulnerability:

The latest beta of Electron 5 was tracking Chromium 73 and therefore is already patched:

Más información

This vulnerability was discovered by Clement Lecigne of Google's Threat Analysis Group and reported to the Chrome team. The Chrome blog post can be found here.

Para aprender más sobre las buenas prácticas para mantener tus aplicaciones Electron seguras, ve nuestro tutorial de seguridad.

Si quieres reportar una vulnerabilidad de Electron, envía un correo electrónico a security@electronjs.org.

Discontinuing support for 32-bit Linux

· 3 lectura mínima

El equipo de Electron suspenderá el soporte para Linux de 32 bits (ia32 / i386) a partir de Electron v4.0. La última versión de Electron que soporta instalaciones basadas en 32 bits de Linux es Electron v3.1, que recibirá versiones de soporte hasta que Electron v6 sea liberado. Support for 64-bit based Linux and armv7l will continue unchanged.


What exactly is Electron no longer supporting?

You may have seen the description "64-bit" and "32-bit" as stickers on your computer or as options for downloading software. The term is used to describe a specific computer architecture. Most computers made in the 1990s and early 2000s were made with CPUs that were based on the 32-bit architecture, while most computers made later were based on the newer and more powerful 64-bit architecture. The Nintendo 64 (get it?) and the PlayStation 2 were the first widely available consumer devices with the new architecture, computers sold after 2010 contained almost exclusively 64-bit processors. As a result, support has been shrinking: Google stopped releasing Chrome for 32-bit Linux in March 2016, Canonical stopped providing 32-bit desktop images in 2017 and dropped support for 32-bit altogether with Ubuntu 18.10. Arch Linux, elementary OS, and other prominent Linux distributions have already dropped support for the aging processor architecture.

Until now, Electron has provided and supported builds that run on the older 32-bit architecture. From release v4.0 onwards, the Electron team will no longer be able to provide binaries or support for 32-bit Linux.

Electron has always been a vibrant open source project and we continue to support and encourage developers interested in building Electron for exotic architectures.

What does that mean for developers?

If you are not currently providing 32-bit distributions of your app for Linux, no action is required.

Projects which ship 32-bit Linux Electron applications will need to decide how to proceed. 32-bit Linux will be supported on Electron 3 until the release of Electron 6, which gives some time to make decisions and plans.

What does that mean for users?

If you are a Linux user and not sure whether or not you're running a 64-bit based system, you are likely running on a 64-bit based architecture. To make sure, you can run the lscpu or uname -m commands in your terminal. Either one will print your current architecture.

If you are using Linux on a 32-bit processor, you have likely already encountered difficulties finding recently released software for your operating system. The Electron team joins other prominent members in the Linux community by recommending that you upgrade to a 64-bit based architecture.

BrowserView window.open() Vulnerability Fix

· Lectura de un minuto

A code vulnerability has been discovered that allows Node to be re-enabled in child windows.


Opening a BrowserView with sandbox: true or nativeWindowOpen: true and nodeIntegration: false results in a webContents where window.open can be called and the newly opened child window will have nodeIntegration enabled. This vulnerability affects all supported versions of Electron.

Mitigación

We've published new versions of Electron which include fixes for this vulnerability: 2.0.17, 3.0.15, 3.1.3, 4.0.4, and 5.0.0-beta.2. We encourage all Electron developers to update their apps to the latest stable version immediately.

If for some reason you are unable to upgrade your Electron version, you can mitigate this issue by disabling all child web contents:

view.webContents.on('-add-new-contents', (e) => e.preventDefault());

Más información

This vulnerability was found and reported responsibly to the Electron project by PalmerAL.

Para aprender más sobre las buenas prácticas para mantener tus aplicaciones Electron seguras, ve nuestro tutorial de seguridad.

Si quieres reportar una vulnerabilidad de Electron, envía un correo electrónico a security@electronjs.org.

Node.js Native Addons and Electron 5.0

· 2 lectura mínima

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.

Ayuda! 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 lectura mínima

Por primera vez en la historia, Electron está emocionado de dar a conocer nuestro programa de lanzamiento a partir de la v5. Este es nuestro primer paso para tener una cronología pública a largo plazo.


Como se menciona en nuestra versión estable v 4.0.0 publicación de blog, estamos planeando lanzarla aproximadamente trimestralmente para Mantén una cadencia más cercana con los lanzamientos de Chromium.

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.

Con esto en mente, estamos dando los primeros pasos publicando nuestro calendario de lanzamiento para v5.0.0. Puedes encontrar eso aquí.

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

Electron 4.0.0

· 7 lectura mínima

¡ El equipo de electrones se complace en anunciar que el lanzamiento estable de Electron 4 ya está disponible! Puedes instalarlo desde electronjs.org o desde npm a través de npm install electron@latest. El lanzamiento está repleto de actualizaciones, correcciones y nuevas características, y no podemos esperar a ver lo que construyes con ellos. ¡Lea más para obtener más información sobre esta versión, y por favor comparta cualquier comentario que tenga mientras explora!


What's New?

Una gran parte de la funcionalidad de Electron es proporcionada por Chromium, Node.js y V8, los componentes principales que componen Electron. Como tal, un objetivo clave para el equipo de Electron es mantenerse al día con los cambios en estos proyectos tanto como sea posible proporcionando a los desarrolladores que construyen aplicaciones Electron acceso a nuevas características web y JavaScript. Con este fin, Electron 4 presenta los principales saltos de versión de cada uno de estos componentes; Electron v 4.0.0 incluye 69.0.3497.106de cromo, 10.11.0de nodo y 6.9.427.24V8.

Además, Electron 4 incluye cambios en las APIs específicas de Electron. Puedes encontrar un resumen de los cambios principales en Electron 4 a continuación; para ver la lista completa de cambios, revisa las notas de lanzamiento de Electron v 4.0.0.

Deshabilitar el módulo remote

Ahora tiene la habilidad de desactivar el módulo remote por razones de seguridad. El módulo puede ser deshabilitado para etiquetas BrowserWindows y webview:

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

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

Consulte la documentación de BrowserWindow y <webview> Tag para más información.

Filtrando remote.require() / remote.getGlobal() solicitudes

Esta característica es útil si no desea deshabilitar completamente el módulo remote en su proceso de renderizado o webview pero le gustaría un control adicional sobre qué módulos pueden ser requeridos vía remote.require.

Cuando se requiere un módulo a través de remote.require en un proceso de renderizado, se eleva un evento remote-require en el módulo app. Puede llamar a event.preventDefault() en el evento (el primer argumento) para evitar que el módulo sea cargado. La WebContents instancia donde ocurrió la solicitud es pasada como el segundo argumento, y el nombre del módulo es pasado como el tercer argumento. El mismo evento también se emite en la instancia de WebContents, pero en este caso, los únicos argumentos son el evento y el nombre del módulo. En ambos casos, puede devolver un valor personalizado estableciendo el valor de event.returnValue.

// Controla `remote.require` desde todos los 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) {
// ...
},
);

De una manera similar, cuando se llama a remote.getGlobal(name), se levanta un evento remote-get-global. Esto funciona del mismo modo que el evento remote-require: llame a preventDefault() para evitar que el global sea devuelto, y establece event.returnValue para retornar un valor personalizado.

// 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) {
// ...
},
);

Para obtener más información, consulte la siguiente documentación:

JavaScript Access to the About Panel

En macOS, ahora puede llamar a app.showAboutPanel() para mostrar programáticamente el panel Acerca, al igual que hacer clic en el elemento de menú creado a través de {role: 'about'}. Vea la documentación de showAboutPanel para más información

Controlando WebContents Limitando el segundo plano

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(enableBackgroundThrottling)
win.webContents.setBackgroundThrottling(enableBackgroundThrottling)

See the setBackgroundThrottling documentation for more information.

Restaurar archivos borrados

No más soporte para macOS 10.9

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.

Programa de retroalimentación

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.

What's Next

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.

SQLite Vulnerability Fix

· Lectura de un minuto

A remote code execution vulnerability, "Magellan," has been discovered affecting software based on SQLite or Chromium, including all versions of Electron.


Ámbito

Electron applications using Web SQL are impacted.

Mitigación

Affected apps should stop using Web SQL or upgrade to a patched version of Electron.

We've published new versions of Electron which include fixes for this vulnerability:

There are no reports of this in the wild; however, affected applications are urged to mitigate.

Más información

This vulnerability was discovered by the Tencent Blade team, who have published a blog post that discusses the vulnerability.

Para aprender más sobre las buenas prácticas para mantener tus aplicaciones Electron seguras, ve nuestro tutorial de seguridad.

Si quieres reportar una vulnerabilidad de Electron, envía un correo electrónico a security@electronjs.org.

Programa de Retroalimentación de la Aplicación Electron

· 3 lectura mínima

Estamos trabajando en hacer el ciclo de desarrollo de Electrón más rápido y estable. Para hacerlo posible, hemos iniciado el Programa de Comentarios de Aplicaciones para aplicaciones Electron a gran escala para probar nuestras versiones beta y reportarnos problemas específicos de la aplicación. Esto nos ayuda a priorizar el trabajo que hará que las aplicaciones se actualicen antes a nuestra próxima versión estable.

Edición (2020-05-21): Este programa ha sido retirado.


¿Quién puede unirse?

Nuestros criterios y expectativas para que las aplicaciones se unan a este programa incluyen los siguientes elementos:

  • Prueba tu aplicación durante el periodo beta durante más de 10.000 horas
  • Tener una persona de un solo punto que chequee semanalmente para discutir los errores de su aplicación Electron y bloqueadores de aplicaciones
  • Aceptas acatar el Código de Conducta de Electron
  • Está dispuesto a compartir la siguiente información listada en la siguiente pregunta

¿Qué información debe compartir mi aplicación Electron?

  • Total de horas de funcionamiento de su aplicación con cualquier versión beta
  • Versión de Electron con la que está probando su aplicación (por ejemplo, 4.0.0-beta.3)
  • Cualquier error que impida que su aplicación de actualizar a la línea de publicación sea probado

Usuario / Horas

Entendemos que no todos pueden compartir números de usuario exactos, sin embargo mejores datos nos ayudan a decidir cuán estable es una versión en particular. Pedimos que las aplicaciones se comprometan a probar un número mínimo de horas de usuario, actualmente 10.000 en todo el ciclo beta.

  • 10 horas de usuario podrían ser 10 personas probando por una hora, o una persona probando por 10 horas
  • Puede dividir la prueba entre versiones beta, por ejemplo prueba de 5.000 horas de usuario en 3.0.0-beta. y luego pruebe por 5.000 horas de usuario en 3.0.0-beta.5. Más es mejor, pero entendemos que algunas aplicaciones no pueden probar cada versión beta
  • Las horas CI o QA no cuentan para el total; sin embargo, las versiones internas cuentan

¿Por qué debería unirse mi aplicación Electron?

Los errores de tu aplicación serán rastreados y estarán en el radar del núcleo del equipo de Electron. Sus comentarios ayudan al equipo de Electron a ver cómo están haciendo las nuevas betas y qué trabajo hay que hacer.

¿Se compartirá la información de mi aplicación públicamente? ¿Quién puede ver esta información?

No, la información de su aplicación no se compartirá con el público en general. La información se mantiene en un repositorio privado de GitHub que sólo es visible para los miembros del Programa de Comentarios de la aplicación y Gobernanza Electron. Todos los miembros han aceptado seguir el Código de Conducta de Electron.

Registrarse

Actualmente estamos aceptando un número limitado de registros. Si está interesado y puede cumplir con los requisitos anteriores, por favor rellene este formulario.