Selaa lähdekoodia

feat: use a preload script instead of enabling nodeIntegration (#279)

Mark Lee 6 vuotta sitten
vanhempi
commit
19788f8fbe
3 muutettua tiedostoa jossa 14 lisäystä ja 9 poistoa
  1. 5 8
      index.html
  2. 2 1
      main.js
  3. 7 0
      preload.js

+ 5 - 8
index.html

@@ -6,14 +6,11 @@
   </head>
   <body>
     <h1>Hello World!</h1>
-    <!-- All of the Node.js APIs are available in this renderer process. -->
-    We are using Node.js <script>document.write(process.versions.node)</script>,
-    Chromium <script>document.write(process.versions.chrome)</script>,
-    and Electron <script>document.write(process.versions.electron)</script>.
+    We are using Node.js <span id="node-version"></span>,
+    Chromium <span id="chrome-version"></span>,
+    and Electron <span id="electron-version"></span>.
 
-    <script>
-      // You can also require other files to run in this process
-      require('./renderer.js')
-    </script>
+    <!-- You can also require other files to run in this process -->
+    <script src="./renderer.js"></script>
   </body>
 </html>

+ 2 - 1
main.js

@@ -1,5 +1,6 @@
 // Modules to control application life and create native browser window
 const {app, BrowserWindow} = require('electron')
+const path = require('path')
 
 // 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.
@@ -11,7 +12,7 @@ function createWindow () {
     width: 800,
     height: 600,
     webPreferences: {
-      nodeIntegration: true
+      preload: path.join(__dirname, 'preload.js')
     }
   })
 

+ 7 - 0
preload.js

@@ -0,0 +1,7 @@
+// All of the Node.js APIs are available in the preload process.
+// It has the same sandbox as a Chrome extension.
+window.addEventListener('DOMContentLoaded', () => {
+  for (const versionType of ['chrome', 'electron', 'node']) {
+    document.getElementById(`${versionType}-version`).innerText = process.versions[versionType]
+  }
+})