Browse Source

Add window.loadFile and webContents.loadFile helper methods

Samuel Attard 7 years ago
parent
commit
1553b54779

+ 8 - 0
docs/api/browser-window.md

@@ -1159,6 +1159,14 @@ win.loadURL('http://localhost:8000/post', {
 })
 ```
 
+#### `win.loadFile(filePath)`
+
+* `filePath` String
+
+Same as `webContents.loadFile`, `filePath` should be a path to an HTML
+file relative to the root of your application.  See the `webContents` docs
+for more information.
+
 #### `win.reload()`
 
 Same as `webContents.reload`.

+ 22 - 0
docs/api/web-contents.md

@@ -625,6 +625,28 @@ const options = {extraHeaders: 'pragma: no-cache\n'}
 webContents.loadURL('https://github.com', options)
 ```
 
+#### `contents.loadFile(filePath)`
+
+* `filePath` String
+
+Loads the given file in the window, `filePath` should be a path to
+an HTML file relative to the root of your application.  For instance
+an app structure like this:
+
+```
+| root
+| - package.json
+| - src
+|   - main.js
+|   - index.html
+```
+
+Would require code like this
+
+```js
+win.loadFile('src/index.html')
+```
+
 #### `contents.downloadURL(url)`
 
 * `url` String

+ 3 - 0
lib/browser/api/browser-window.js

@@ -169,6 +169,9 @@ Object.assign(BrowserWindow.prototype, {
   getURL (...args) {
     return this.webContents.getURL()
   },
+  loadFile (filePath) {
+    return this.webContents.loadFile(filePath)
+  },
   reload (...args) {
     return this.webContents.reload(...args)
   },

+ 13 - 0
lib/browser/api/web-contents.js

@@ -2,6 +2,8 @@
 
 const {EventEmitter} = require('events')
 const electron = require('electron')
+const path = require('path')
+const url = require('url')
 const {app, ipcMain, session, NavigationController} = electron
 
 // session is not used here, the purpose is to make sure session is initalized
@@ -243,6 +245,17 @@ WebContents.prototype.getZoomLevel = function (callback) {
   })
 }
 
+WebContents.prototype.loadFile = function (filePath) {
+  if (typeof filePath !== 'string') {
+    throw new Error('Must pass filePath as a string')
+  }
+  return this.loadURL(url.format({
+    protocol: 'file',
+    slashes: true,
+    pathname: path.resolve(app.getAppPath(), filePath)
+  }))
+}
+
 WebContents.prototype.getZoomFactor = function (callback) {
   if (typeof callback !== 'function') {
     throw new Error('Must pass function as an argument')