Table of contents
3. Using Preload Scripts
What is a preload script?
Electron์ ๋ฉ์ธ ํ๋ก์ธ์ค๋ ์ ์ฒด ์ด์ ์ฒด์ ์ ์ก์ธ์คํ ์ ์๋ Node.js ํ๊ฒฝ์ด๋ค. Electron ๋ชจ๋๋ฟ๋ง ์๋๋ผ npm์ ํตํด ์ค์นํ ํจํค์ง๋ Node.js์ ๊ธฐ๋ณธ ๋ด์ฅ ๋ชจ๋์๋ ์ก์ธ์คํ ์ ์๋ค. ๋ฐ๋ฉด์, ๋ณด์์์ ์ด์ ๋ก ๋ ๋๋ฌ ํ๋ก์ธ์ค๋ ๊ธฐ๋ณธ์ ์ผ๋ก Node.js๋ฅผ ์คํํ์ง ์๊ณ ์น ํ์ด์ง๋ฅผ ์คํํ๋ค.
Electron์ ๋ค๋ฅธ ํ๋ก์ธ์ค ์ ํ์ ํจ๊ป ์ฐ๊ฒฐํ๋ ค๋ฉด preload๋ผ๊ณ ๋ถ๋ฆฌ๋ ํน์ํ ์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค.
Augmenting the renderer with a preload script
preload.js
preload script๋ ๋ ๋๋ฌ์์ ์น ํ์ด์ง๊ฐ ๋ก๋๋๊ธฐ ์ ์ ์ฃผ์
๋๋ฉฐ, ์ด๋ ํฌ๋กฌ ์ต์คํ
์
์ ์ปจํ
ํธ ์คํฌ๋ฆฝํธ์ ์ ์ฌํ๋ค. ํน๊ถ ์๋ ์ก์ธ์ค๊ฐ ํ์ํ ๋ ๋๋ฌ์ ๊ธฐ๋ฅ์ ์ถ๊ฐํ๋ ค๋ฉด contextBridge API๋ฅผ ์ฌ์ฉํ์ฌ ์ ์ญ ๊ฐ์ฒด๋ฅผ ์ ์ํ ์ ์๋ค.
์ฝ๋๋ณด๊ธฐ
//preload.js
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node,
chrome: () => process.versions.chrome,
electron: () => process.versions.electron
// we can also expose variables, not just functions
})
์คํํ๋ฉด
main.js
์ด ์คํฌ๋ฆฝํธ๋ฅผ ๋ ๋๋ฌ ํ๋ก์ธ์ค์ ์ฐ๊ฒฐํ๋ ค๋ฉด BrowserWindow ์์ฑ์์ webPreferences.preload ์ต์ ์ ํด๋น ์คํฌ๋ฆฝํธ์ ๊ฒฝ๋ก๋ฅผ ์ ๋ฌํ๋ฉด ๋๋ค.
์ฝ๋๋ณด๊ธฐ
//main.js
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
์คํํ๋ฉด
renderer.js
ํ์ฌ ์์ ์์ ๋ ๋๋ฌ๋ versions ์ ์ญ ๋ณ์์ ์ก์ธ์คํ ์ ์๋ค. ์ด ์ ๋ณด๋ฅผ ์ฐฝ์ ํ์ํด ๋ณด๊ฒ ๋ค. ์ด ๋ณ์๋ window.versions ๋๋ ๊ฐ๋จํ versions๋ฅผ ํตํด ์ก์ธ์คํ ์ ์์ต๋๋ค. info๋ผ๋ id ์์ฑ์ ๊ฐ์ง HTML ์์์ ํ ์คํธ๋ฅผ ๋ณ๊ฒฝํ๋ ๋ฐ๋ document.getElementById DOM API๋ฅผ ์ฌ์ฉํ๊ฒ ๋ค.
์ฝ๋๋ณด๊ธฐ
//renderer.js
const information = document.getElementById('info')
information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`
์คํํ๋ฉด
index.html
index.html์ ์์ ํ์ฌ id ์์ฑ์ด โinfoโ์ธ ์๋ก์ด ์์๋ฅผ ์ถ๊ฐํ๊ณ , renderer.js ์คํฌ๋ฆฝํธ๋ฅผ ์ฐ๊ฒฐ
์ฝ๋๋ณด๊ธฐ
#index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<title>Hello from Electron renderer!</title>
</head>
<body>
<h1>Hello from Electron renderer!</h1>
<p>๐</p>
<p id="info"></p>
</body>
<script src="./renderer.js"></script>
</html>
์คํํ๋ฉด
์คํ๊ฒฐ๊ณผ
ํ๋ก์ ํธ ํธ๋ฆฌ