fs
내 renderer
프로세스에서 다음과 같이 노드 모듈 (이 예에서는 ) 을 사용하려고합니다 .
// main_window.js
const fs = require('fs')
function action() {
console.log(fs)
}
참고 : action
내 버튼을 누르면 함수가 호출됩니다 main_window
.
그러나 이것은 오류를 제공합니다 :
Uncaught ReferenceError: require is not defined
at main_window.js:1
이 허용 된 답변 에서 제안한대로 다음을 main.js
초기화 할 때 다음 행을 추가 하여이 문제를 해결할 수 있습니다 main_window
.
// main.js
main_window = new BrowserWindow({
width: 650,
height: 550,
webPreferences: {
nodeIntegration: true
}
})
그러나 docs에 따르면 이것이 최선의 방법은 아니며 대신 preload.js
파일을 만들고이 노드 모듈을로드 한 다음 모든 renderer
프로세스 에서 사용해야합니다 . 이처럼 :
main.js
:
main_window = new BrowserWindow({
width: 650,
height: 550,
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
preload.js
:
const fs = require('fs')
window.test = function() {
console.log(fs)
}
main_window.js
:
function action() {
window.test()
}
그리고 작동합니다!
이제 내 질문에 내가 내의 대부분의 코드 작성해야한다는, 반 직관적이지 그것입니다 renderer
에서 프로세스 preload.js
(에서만 때문에 preload.js
내가 노드 모듈에 액세스 할 수 있습니다) 다음 단순히 각각의 함수를 호출 renderer.js
파일 (여기 예를 들어 main_window.js
) ? 내가 여기서 이해하지 못하는 것은 무엇입니까?
다른 사용자가 물을 때 아래에 내 대답을 설명하겠습니다.
preload.js
Electron에서 사용하는 올바른 방법 은 앱에 필요한 모든 모듈 주위에 화이트리스트 래퍼를 노출시키는 것 require
입니다.
보안 측면에서 require
, 또는 require
전화를 통해 검색 한 내용 을 노출하는 것은 위험 합니다 preload.js
(자세한 내용은 여기 내 의견 참조 ). 앱이 원격 콘텐츠를로드하는 경우 특히 그렇습니다.
올바른 작업을 수행하려면 BrowserWindow
아래에 자세히 설명 된대로 많은 옵션을 활성화해야 합니다. 이러한 옵션을 설정하면 전자 앱이 IPC (프로세스 간 통신)를 통해 통신하고 두 환경이 서로 분리됩니다. 이와 같이 앱을 설정하면 require
백엔드에서 'd 모듈 일 수있는 모든 것을 검증 할 수 있으며 , 클라이언트가 변조하지 않아도됩니다.
아래에는 내가 말한 내용과 앱에서 어떻게 보일 수 있는지에 대한 간단한 예가 나와 있습니다. 새로 시작 secure-electron-template
하는 경우 전자 응용 프로그램을 만들 때 얻을 수있는 모든 보안 모범 사례가있는 (저는 저자입니다) 사용 하는 것이 좋습니다 .
이 페이지 에는 preload.js를 사용하여 안전한 앱을 만들 때 필요한 아키텍처에 대한 유용한 정보도 있습니다.
main.js
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
index.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");
</script>
</body>
</html>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다