Интеграция HTML, CSS и JavaScript
Разберитесь, как стандартные веб-технологии формируют основу пользовательского интерфейса Electron и позволяют применять уже имеющиеся знания веб-разработки.
«Интеграция HTML, CSS и JavaScript» — бесплатный урок Electron Desktop App Development на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Electron Desktop App Development, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Electron Desktop App Development содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Web UI with HTML, CSS, JS
Welcome! In Electron, you build desktop app interfaces using the same technologies you'd use for a website: HTML, CSS, and JavaScript.
This means your existing web development skills are directly transferable. Let's see how!
Meet the Renderer Process
An Electron app has a Main Process and one or more Renderer Processes.
- The Main Process handles native OS interactions.
- The Renderer Process is essentially a Chromium web browser instance. It's where your HTML, CSS, and JavaScript run, forming your app's user interface.
Think of each Electron window as its own renderer process.
HTML for Structure & Content
HTML (HyperText Markup Language) is the backbone of any web page, including your Electron app's UI.
It defines the structure and content:
- Headings (
<h1>,<h2>) - Paragraphs (
<p>) - Buttons (
<button>)
It's like the blueprint for your app's layout.
Displaying HTML Content
Your Electron main process loads an HTML file into a renderer process (a new window). This HTML file becomes your app's initial view.
Here's how `main.js` loads a simple `index.html` file:
The `index.html` might contain:<h1>Hello Electron!</h1><p>My first desktop UI.</p>
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
// Load the index.html file
win.loadFile(path.join(__dirname, 'index.html'));
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});CSS for Styling Your UI
CSS (Cascading Style Sheets) is used to control the presentation of your HTML content. It dictates how your app looks.
With CSS, you can define:
- Colors and backgrounds
- Fonts and text sizes
- Layout (margins, padding, positioning)
It turns your HTML blueprint into a visually appealing interface.
Linking & Applying Styles
You link a CSS file to your HTML using a <link> tag in the <head> section of your `index.html`.
For example, to style the previous `h1` element:
Your `index.html` would include:<link rel="stylesheet" href="style.css">
And `style.css` could contain:h1 { color: #3366ff; text-align: center; }
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
win.loadFile(path.join(__dirname, 'index.html'));
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});JavaScript for Interactivity
JavaScript (JS) adds dynamic behavior and interactivity to your Electron app's UI.
It allows you to:
- Respond to user actions (clicks, key presses)
- Manipulate HTML content and CSS styles
- Fetch data from APIs
JS turns a static page into a dynamic, responsive application.
Implementing UI Logic with JS
You can embed JavaScript directly in your HTML using <script> tags or link external .js files.
Let's add a button and make it display an alert when clicked:
Your `index.html` would include:<button id="myButton">Click Me!</button><script>document.getElementById('myButton').addEventListener('click', () => { alert('Hello from Electron!'); });</script>
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
win.loadFile(path.join(__dirname, 'index.html'));
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});HTML, CSS, JS: A Unified Stack
Together, HTML, CSS, and JavaScript form a powerful and familiar stack for building Electron user interfaces.
- HTML provides the content and structure.
- CSS defines the visual presentation.
- JavaScript adds interactivity and dynamic behavior.
This allows web developers to leverage their existing knowledge to create robust desktop applications.
Web Tech Roles
Which of the following statements correctly describe the role of HTML, CSS, and JavaScript in an Electron renderer process?
Recap: Web UI Basics
Today, we learned that Electron uses familiar web technologies – HTML, CSS, and JavaScript – to build desktop application user interfaces.
- The renderer process is where these web technologies run.
- HTML structures the content.
- CSS styles the appearance.
- JavaScript adds dynamic behavior.
You now understand the fundamental building blocks of an Electron UI. Next, we'll explore how to integrate popular frontend frameworks.
Часто задаваемые вопросы
Урок «Интеграция HTML, CSS и JavaScript» бесплатный?
Да — полный текст урока «Интеграция HTML, CSS и JavaScript» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Electron Desktop App Development, подпишись на CoddyKit PRO. Курс Electron Desktop App Development содержит 4 уроков всего.
Чему я научусь в уроке «Интеграция HTML, CSS и JavaScript»?
Разберитесь, как стандартные веб-технологии формируют основу пользовательского интерфейса Electron и позволяют применять уже имеющиеся знания веб-разработки. Ты практикуешь Electron Desktop App Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Electron Desktop App Development?
Предыдущий опыт не требуется. Electron Desktop App Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Интеграция HTML, CSS и JavaScript»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Electron Desktop App Development?
Да. Каждый урок Electron Desktop App Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Интеграция HTML, CSS и JavaScript
- Использование фронтенд-фреймворков
- Адаптивный дизайн настольных приложений
- Темы оформления и поддержка тёмного режима