- Electron require () не определен
- пример
- Эта проблема
- Как выглядит проблема
- Какое у нас решение
- Отказ от ответственности
- Electron FAQ
- Why am I having trouble installing Electron?#
- When will Electron upgrade to latest Chrome?#
- When will Electron upgrade to latest Node.js?#
- How to share data between web pages?#
- My app’s tray disappeared after a few minutes.#
- I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.#
- require(‘electron’).xxx is undefined.#
- The font looks blurry, what is this and what can I do?#
- Node Integration not working in Electron?
- Electron IPC and nodeIntegration
- 1 Answer 1
- Electron require() is not defined
- 9 Answers 9
- The problem
- What does the problem look like
- What our solution is
- Disclaimer
Electron require () не определен
Я создаю приложение Electron для своих собственных целей. Моя проблема в том, что когда я использую функции узла внутри своей HTML-страницы, возникает ошибка:
Есть ли способ использовать функции узла на всех моих HTML-страницах? Если возможно, дайте мне пример, как это сделать, или дайте ссылку. Вот переменные, которые я пытаюсь использовать на своей HTML-странице:
и это значения, которые я использую во всех своих окнах HTML в Electron.
Начиная с версии 5, значение по умолчанию для nodeIntegration изменено с true на false. Вы можете включить его при создании окна браузера:
По соображениям безопасности вы должны сохранить nodeIntegration: false и использовать сценарий предварительной загрузки, чтобы предоставлять только то, что вам нужно от Node / Electron API, процессу визуализации (представлению) через переменную окна. Из документов Electron :
Скрипты предварительной загрузки по-прежнему имеют доступ require и к другим функциям Node.js.
пример
main.js
preload.js
renderer.js
Я надеюсь, что этот ответ привлечет некоторое внимание, потому что подавляющее большинство ответов здесь оставляют большие дыры в безопасности в вашем электронном приложении. Фактически, этот ответ — это то, что вы должны делать, чтобы использовать require() в своих электронных приложениях. (Есть только новый электронный API, который делает его немного чище в версии 7).
Я написал подробное объяснение / решение в github, используя самый последний электронный API того, как вы можете require() что-то сделать, но я кратко объясню здесь, почему вы должны следовать подходу с использованием сценария предварительной загрузки, contextBridge и ipc.
Эта проблема
Приложения Electron великолепны, потому что мы можем использовать узел, но эта сила — палка о двух концах. Если мы не будем осторожны, мы дадим кому-то доступ к узлу через наше приложение, и с помощью узла злоумышленник может повредить вашу машину или удалить файлы вашей операционной системы (среди прочего, я полагаю).
Как отметил @raddevus в комментарии, это необходимо при загрузке удаленного контента. Если ваше электронное приложение полностью автономно / локально , вы, вероятно, можете просто включить его nodeIntegration:true . Тем не менее, я бы по-прежнему предпочел nodeIntegration:false действовать в качестве защиты от случайных / злонамеренных пользователей, использующих ваше приложение, и предотвращать взаимодействие любых возможных вредоносных программ, которые могут когда-либо устанавливаться на вашем компьютере, с вашим электронным приложением и использовать nodeIntegration:true вектор атаки (невероятно редко , но могло случиться)!
Как выглядит проблема
Эта проблема проявляется, когда вы (любой из перечисленных ниже):
- Были ли nodeIntegration:true включен
- Используйте remote модуль
Все эти проблемы обеспечивают непрерывный доступ к узлу из вашего процесса рендеринга. Если ваш процесс рендеринга когда-либо будет взломан, вы можете считать, что все потеряно.
Какое у нас решение
Решение состоит в том, чтобы не давать рендереру прямой доступ к узлу (т. Е. require() ), А предоставить нашему электронному основному процессу доступ require и в любое время, когда нашему процессу рендеринга потребуется его использовать require , маршалировать запрос к основному процессу.
В последних версиях (7+) Electron это работает так: на стороне рендерера мы настраиваем привязки ipcRenderer , а на основной стороне мы настраиваем привязки ipcMain . В привязках ipcMain мы настраиваем методы прослушивателя, которые используют модули, которые мы require() . Это нормально, потому что наш основной процесс может require все, что угодно.
Мы используем contextBridge для передачи привязок ipcRenderer к коду нашего приложения (для использования), и поэтому, когда нашему приложению необходимо использовать require модули d в основном, оно отправляет сообщение через IPC (межпроцессное взаимодействие) и запускается основной процесс. какой-то код, а затем мы отправляем сообщение с нашим результатом.
Примерно вот что вы хотите сделать.
main.js
preload.js
index.html
Отказ от ответственности
Я автор secure-electron-template безопасного шаблона для создания электронных приложений. Мне небезразлична эта тема, и я работаю над ней несколько недель (на данный момент).
Источник
Electron FAQ
Why am I having trouble installing Electron?#
When running npm install electron , some users occasionally encounter installation errors.
In almost all cases, these errors are the result of network problems and not actual issues with the electron npm package. Errors like ELIFECYCLE , EAI_AGAIN , ECONNRESET , and ETIMEDOUT are all indications of such network problems. The best resolution is to try switching networks, or wait a bit and try installing again.
You can also attempt to download Electron directly from electron/electron/releases if installing via npm is failing.
When will Electron upgrade to latest Chrome?#
The Chrome version of Electron is usually bumped within one or two weeks after a new stable Chrome version gets released. This estimate is not guaranteed and depends on the amount of work involved with upgrading.
Only the stable channel of Chrome is used. If an important fix is in beta or dev channel, we will back-port it.
For more information, please see the security introduction.
When will Electron upgrade to latest Node.js?#
When a new version of Node.js gets released, we usually wait for about a month before upgrading the one in Electron. So we can avoid getting affected by bugs introduced in new Node.js versions, which happens very often.
New features of Node.js are usually brought by V8 upgrades, since Electron is using the V8 shipped by Chrome browser, the shiny new JavaScript feature of a new Node.js version is usually already in Electron.
How to share data between web pages?#
To share data between web pages (the renderer processes) the simplest way is to use HTML5 APIs which are already available in browsers. Good candidates are Storage API, localStorage , sessionStorage , and IndexedDB.
Alternatively, you can use the IPC primitives that are provided by Electron. To share data between the main and renderer processes, you can use the ipcMain and ipcRenderer modules. To communicate directly between web pages, you can send a MessagePort from one to the other, possibly via the main process using ipcRenderer.postMessage() . Subsequent communication over message ports is direct and does not detour through the main process.
My app’s tray disappeared after a few minutes.#
This happens when the variable which is used to store the tray gets garbage collected.
If you encounter this problem, the following articles may prove helpful:
If you want a quick fix, you can make the variables global by changing your code from this:
I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.#
Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module , exports , require . This causes problems for some libraries since they want to insert the symbols with the same names.
To solve this, you can turn off node integration in Electron:
But if you want to keep the abilities of using Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:
require(‘electron’).xxx is undefined.#
When using Electron’s built-in module you might encounter an error like this:
It is very likely you are using the module in the wrong process. For example electron.app can only be used in the main process, while electron.webFrame is only available in renderer processes.
The font looks blurry, what is this and what can I do?#
If sub-pixel anti-aliasing is deactivated, then fonts on LCD screens can look blurry. Example:
Sub-pixel anti-aliasing needs a non-transparent background of the layer containing the font glyphs. (See this issue for more info).
To achieve this goal, set the background in the constructor for BrowserWindow:
The effect is visible only on (some?) LCD screens. Even if you don’t see a difference, some of your users may. It is best to always set the background this way, unless you have reasons not to do so.
Notice that just setting the background in the CSS does not have the desired effect.
Источник
Node Integration not working in Electron?
I am creating an inventory application with the backend written in Python 3.7. I am using Electron to build a GUI for it and the Node.js Module «python-shell» to be able to communicate with the Python code. I would like for all of the code for python-shell to be in a separate JavaScript file (connector.js). If I run just that file with node from the command line it works perfectly fine, but calling the function from an HTML Button doesn’t work.
I know that with one of the last updates to Electron nodeIntegration by default is false, but I did set that to true. Unfortunately it still doesn’t allow me to communicate with the Node module within the Electron renderer process. If I copy the connector.js code into the main.js file used by Electron and call it on start of the application, it does work but calling it using an HTML button also obviously doesn’t work.
This is the main.js file for Electron with nodeIntegration set to true.
And this is the connector.js file that calls the Python script with the correct arguments. functionality.py is for testing a very simple script that takes the first commandline argument (in this case addNewDataset ) to call a function and the second as the name of a file it creates.
It is loaded into the HTML file using a simple script tag
and called using an input
I am pretty sure that I am just misunderstanding the way Electron and the main and renderer processes work. Unfortunately no matter what I look for on the Internet I don’t seem to be able to get a solution that actually works.
Источник
Electron IPC and nodeIntegration
So, I’ve followed a number of guides to set up Webpack, Electron, and React to make a desktop application. After finishing the setup, I got to work, and learned that I needed to require an IPC mechanism from the main and renderer in order to communicate.
import
After taking my problem to some colleagues, it was suggested that in my main.js file I should change
Everywhere I’ve read on google has said very clearly that if safety is something you care about, this is not something you should do. However, every resource I’ve been able to come across for electron ipc has used the ipcRenderer.
Now, does every example on the internet have huge security flaws, or am I missing some key part here?
My questions are as follows.
- Is it possible to use ipcRenderer without enabling nodeIntegration?
- If it is, how do I do it, and why would so many resources exclude this information?
- If it is not, what do I use?
If I’m asking the wrong question, or I missed something, or there are any other clear problems with the way I’ve asked this question please let me know, otherwise thanks in advance.
1 Answer 1
- Is it possible to use ipcRenderer without enabling nodeIntegration?
It is possible, but fiddly. It can be done by using a preload script.
- If it is, how do I do it, and why would so many resources exclude this information?
It is possible, using the preload script as indicated below. However, this is not considered secure. Most of the existing documentation does not show best security practices.
A more secure example is given afterwards.
NOTE That the path to the preload script must be absolute and this can also get complicated when using webpack/babel, as the output file may be a different path.
Edit As @Yannic pointed out, there is now another option supported by Electron, called contextBridge . This new option may solve the problem more simply. For info on contextBridge , check the electron docs: https://www.electronjs.org/docs/tutorial/context-isolation
However, even with contextBridge you should not be try to expose entire electron APIs, just a limited API you have designed for your app
As mentioned, although it is possible to use ipcRenderer as shown above, the current electron security recommendations recommend also enabling contextIsolation . This will make the above approach unusable as you can no longer add data to the global scope.
The most secure recommendation, AFAIK is to use addEventListener and postMessage instead, and use the preload script as a bridge between the renderer and the main scripts.
Источник
Electron require() is not defined
I’m creating an Electron app for my own purpose. My problem is when I’m using node functions inside my HTML page it throws an error of:
Is there any way to use Node functionalities in all my HTML pages? If it is possible please give me an example of how to do this or provide a link. Here are the variables I’m trying to use in my HTML page:
and these are the values I’m using in all my HTML windows within Electron.
9 Answers 9
As of version 5, the default for nodeIntegration changed from true to false. You can enable it when creating the Browser Window:
I hope this answer gets some attention, because a large majority of answers here leave large security holes in your electron app. In fact this answer is essentially what you should be doing to use require() in your electron apps. (There is just a new electron API that makes it a little bit cleaner in v7).
I wrote a detailed explanation/solution in github using the most current electron apis of how you can require() something, but I’ll explain briefly here why you should follow an approach using a preload script, contextBridge and ipc.
The problem
Electron apps are great because we get to use node, but this power is a double-edged sword. If we are not careful, we give someone access to node through our app, and with node a bad actor can corrupt your machine or delete your operating system files (among other things, I imagine).
As brought up by @raddevus in a comment, this is necessary when loading remote content. If your electron app is entirely offline/local, then you are probably okay simply turning on nodeIntegration:true . I still would, however, opt to keep nodeIntegration:false to act as a safeguard for accidental/malicious users using your app, and prevent any possible malware that might ever get installed on your machine from interacting with your electron app and using the nodeIntegration:true attack vector (incredibly rare, but could happen)!
What does the problem look like
This problem manifests when you (any one of the below):
- Have nodeIntegration:true enabled
- Use the remote module
All of these problems give uninterrupted access to node from your renderer process. If your renderer process is ever hijacked, you can consider all is lost.
What our solution is
The solution is to not give the renderer direct access to node (ie. require() ), but to give our electron main process access to require , and anytime our renderer process needs to use require , marshal a request to the main process.
The way this works in the latest versions (7+) of Electron is on the renderer side we set up ipcRenderer bindings, and on the main side we set up ipcMain bindings. In the ipcMain bindings we set up listener methods that use modules we require() . This is fine and well because our main process can require all it wants.
We use the contextBridge to pass the ipcRenderer bindings to our app code (to use), and so when our app needs to use the require d modules in main, it sends a message via IPC (inter-process-communication) and the main process runs some code, and we then send a message back with our result.
Roughly, here’s what you want to do.
main.js
preload.js
index.html
Disclaimer
I’m the author of secure-electron-template , a secure template to build electron apps. I care about this topic, and have been working on this for a few weeks (at this point in time).
Источник