webContents
Render and control web pages.
Process: Main
webContents is an EventEmitter.
It is responsible for rendering and controlling a web page and is a property of
the BrowserWindow object. An example of accessing the
webContents object:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://github.com')
const contents = win.webContents
console.log(contents)
Navigation Events
Several events can be used to monitor navigations as they occur within a webContents.
Document Navigations
When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigationwill-frame-navigatewill-navigate(only fired when main frame navigates)will-redirect(only fired when a redirect happens during navigation)did-redirect-navigation(only fired when a redirect happens during navigation)did-frame-navigatedid-navigate(only fired when main frame navigates)
Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.
In-page Navigation
In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order:
Frame Navigation
The will-navigate and did-navigate events only fire when the mainFrame navigates.
If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
Methods
These methods can be accessed from the webContents module:
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
Returns WebContents[] - An array of all WebContents instances. This will contain web contents
for all windows, webviews, opened devtools, and devtools extension background pages.
webContents.getFocusedWebContents()
Returns WebContents | null - The web contents that is focused in this application, otherwise
returns null.
webContents.fromId(id)
idInteger
Returns WebContents | undefined - A WebContents instance with the given ID, or
undefined if there is no WebContents associated with the given ID.
webContents.fromFrame(frame)
frameWebFrameMain
Returns WebContents | undefined - A WebContents instance with the given WebFrameMain, or
undefined if there is no WebContents associated with the given WebFrameMain.