컨텍스트 격리 및 사전 로드 스크립트
악성 스크립트로부터 렌더러 프로세스를 보호하도록 컨텍스트 격리를 이해하고 적용하며, 안전한 API 노출에 사전 로드 스크립트를 사용합니다.
컨텍스트 격리 및 사전 로드 스크립트은(는) CoddyKit의 무료 Electron Desktop App Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Electron Desktop App Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Electron Desktop App Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Renderer Process Risks
In Electron, your application's user interface runs in a renderer process. This process is essentially a Chromium web page, meaning it's susceptible to common web vulnerabilities like Cross-Site Scripting (XSS).
- Malicious scripts injected into your web content could potentially gain access to powerful Node.js APIs.
- This direct access could lead to system-level operations being performed without your knowledge or consent.
- Protecting the renderer is crucial for app security.
What is Context Isolation?
Context Isolation is a fundamental security feature in Electron. When enabled, it ensures that the JavaScript context of your web page is completely separate from Electron's internal APIs and Node.js environment.
- It's like having two distinct JavaScript worlds within the same renderer process.
- One world for your web content, and another for Electron/Node.js.
- This separation prevents your web page's scripts from directly accessing sensitive APIs.
Good news: Context Isolation is enabled by default since Electron 12!
Two JavaScript Worlds
Imagine your renderer process has two invisible layers:
- The Web Page Context: This is where your
index.html, its scripts, and any loaded libraries (like React or Vue) run. It behaves just like a regular browser tab. - The Electron/Node.js Context: This is where Electron's internal modules and Node.js APIs (like
fsfor file system access) live.
Context Isolation ensures these two worlds cannot directly interact with each other's global objects (like window or document), preventing unauthorized access.
Bridging Isolated Contexts
While isolation is great for security, sometimes your web page needs to interact with native desktop features. This is where preload scripts come in.
- A preload script runs before your web page loads, but within the Electron/Node.js context.
- It has access to both Node.js APIs and the web page's
windowobject (before isolation takes full effect). - However, to securely expose APIs to the isolated web page, we use a special tool called
contextBridge.
Loading a Preload Script
To use a preload script, you must specify its path when creating your BrowserWindow in the main process. Remember to keep contextIsolation set to true for security.
Try running this basic setup:
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true // Crucial for security!
}
});
mainWindow.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});Secure API Exposure
The contextBridge module is your best friend for securely exposing functionality from your preload script to the renderer's isolated web context.
- It acts as a secure, one-way bridge.
- You define what functions or data you want to expose.
contextBridgeensures that only these defined APIs are available and that data passed between contexts is properly sanitized.
This prevents malicious scripts in the web page from tampering with your exposed APIs or gaining direct access to Node.js.
Crafting Your Preload Script
Inside your preload.js, you'll use contextBridge.exposeInMainWorld(). This method takes two arguments: a key (how the API will be named in the renderer's window object) and an object containing the functions or values you want to expose.
preload.js:
const { contextBridge } = require('electron');
contextBridge.exposeInMainWorld('myAPI', {
// Expose a simple function
sendNotification: (message) => {
// In a real app, you'd use ipcRenderer.send to talk to main process
console.log(`Preload script sending notification: ${message}`);
// Example: new Notification('Title', { body: message });
},
// Expose a value
version: process.versions.electron
});Accessing Exposed APIs
Once your preload script has exposed an API using contextBridge, your web page's JavaScript can safely access it via the window object, under the key you specified.
index.html (or a script loaded by it):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Electron App</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Electron Version: <span id="electron-version"></span></p>
<button id="notify-btn">Send Notification</button>
<script>
// Access the exposed API
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('electron-version').innerText = window.myAPI.version;
document.getElementById('notify-btn').addEventListener('click', () => {
window.myAPI.sendNotification('Hello from the renderer!');
});
});
</script>
</body>
</html>Full Example in Action
Here's the complete main.js for our app. To run this example, create three files: main.js (below), preload.js (content from Scene 7), and index.html (content from Scene 8) in the same directory.
When you run main.js, it will load index.html. The index.html then uses the myAPI object exposed by preload.js to display the Electron version and trigger a 'notification' (logged to console in this simple example).
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true // Keep this true!
}
});
mainWindow.loadFile('index.html');
// Open DevTools to see console logs from preload and renderer
mainWindow.webContents.openDevTools();
}
app.whenReady().then(() => {
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});Context Check
Time to test your understanding of context isolation and preload scripts!
Secure Foundations
You've learned how to secure your Electron application's renderer process!
- Context Isolation is key to preventing direct access between untrusted web content and powerful Node.js APIs.
- Preload scripts run in an isolated environment, allowing you to bridge this gap safely.
contextBridgeis the secure method within preload scripts to expose carefully selected APIs to your web content.
By using these features, you build a robust and secure foundation for your Electron desktop applications. Great job!
자주 묻는 질문
“컨텍스트 격리 및 사전 로드 스크립트” 강의는 무료인가요?
네 — “컨텍스트 격리 및 사전 로드 스크립트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Electron Desktop App Development 강의 전체를 잠금 해제할 수 있습니다. Electron Desktop App Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“컨텍스트 격리 및 사전 로드 스크립트”에서 뭘 배우나요?
악성 스크립트로부터 렌더러 프로세스를 보호하도록 컨텍스트 격리를 이해하고 적용하며, 안전한 API 노출에 사전 로드 스크립트를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Electron Desktop App Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Electron Desktop App Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Electron Desktop App Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“컨텍스트 격리 및 사전 로드 스크립트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Electron Desktop App Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Electron Desktop App Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 안전한 IPC 패턴
- 컨텍스트 격리 및 사전 로드 스크립트
- 렌더러 프로세스 샌드박싱
- 원격 콘텐츠 위험에 대비한 보안 강화