webContents
Render and control web pages.
Процесс: Главный
webContents
является EventEmitter'ом. Он ответственен за рендер и управление веб-страницы и является свойством объекта BrowserWindow
. Пример доступа к объекту webContents
:
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-navigation
will-frame-navigate
will-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-navigate
did-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.
Методы
Эти методы доступны из модуля webContents
:
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
Возвращает WebContents
- массив всех экземпляров WebContents
. Этот массив содержит веб-контент всех окон, webviews, открытых инструментов разработчика и расширений инструментов разработчика на фоновых страницах.
webContents.getFocusedWebContents()
Returns WebContents | null
- The web contents that is focused in this application, otherwise returns null
.
webContents.fromId(id)
id
Integer
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)
frame
WebFrameMain
Returns WebContents | undefined
- A WebContents instance with the given WebFrameMain, or undefined
if there is no WebContents associated with the given WebFrameMain.
webContents.fromDevToolsTargetId(targetId)
targetId
string - The Chrome DevTools Protocol TargetID associated with the WebContents instance.
Returns WebContents | undefined
- A WebContents instance with the given TargetID, or undefined
if there is no WebContents associated with the given TargetID.
When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await wc.fromDevToolsTargetId(targetId)
}
Класс: WebContents
Рендерит и управляет контент экземпляра BrowserWindow.
Процесс: Main
Этот кл асс не экспортируется из модуля 'electron'
. Он доступен только в качестве возвращаемого значения других методов в Electron API.
События экземпляра
Event: 'did-finish-load'
Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload
event was dispatched.
Event: 'did-fail-load'
Возвращает:
- Событие типа
event
errorCode
Integer- строка
errorDescription
- строка
validatedURL
isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
This event is like did-finish-load
but emitted when the load failed. The full list of error codes and their meaning is available here.
Event: 'did-fail-provisional-load'
Возвращает:
- Событие типа
event
errorCode
Integer- строка
errorDescription
- строка
validatedURL
isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
This event is like did-fail-load
but emitted when the load was cancelled (e.g. window.stop()
was invoked).
Event: 'did-frame-finish-load'
Возвращает:
- Событие типа
event
isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when a frame has done navigation.
Событие: 'did-start-loading'
Corresponds to the points in time when the spinner of the tab started spinning.
Событие: 'did-stop-loading'
Corresponds to the points in time when the spinner of the tab stopped spinning.
Событие: 'dom-ready'
Emitted when the document in the top-level frame is loaded.
Событие: 'page-title-updated'
Возвращает:
- Событие типа
event
title
stringexplicitSet
boolean
Fired when page title is set during navigation. explicitSet
is false when title is synthesized from file url.
Событие: 'page-favicon-updated'
Возвращает:
- Событие типа
event
favicons
string[] - Array of URLs.
Emitted when page receives favicon urls.
Event: 'content-bounds-updated'
Возвращает:
- Событие типа
event
bounds
Rectangle - requested new content bounds
Emitted when the page calls window.moveTo
, window.resizeTo
or related APIs.
By default, this will move the window. To prevent that behavior, call event.preventDefault()
.
Event: 'did-create-window'
Возвращает:
window
BrowserWindow- Объект
details
url
string - URL for the created window.frameName
string - Name given to the created window in thewindow.open()
call.referrer
Referrer - The referrer that will be passed to the new window. May or may not result in theReferer
header being sent, depending on the referrer policy.postBody
PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will benull
. Only defined when the window is being created by a form that settarget=_blank
.disposition
string - Can bedefault
,foreground-tab
,background-tab
,new-window
orother
.
Emitted after successful creation of a window via window.open
in the renderer. Not emitted if the creation of the window is canceled from webContents.setWindowOpenHandler
.
See window.open()
for more details and how to use this in conjunction with webContents.setWindowOpenHandler
.
Событие: 'will-navigate'
Возвращает:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalse
for this event.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain - The frame to be navigated.initiator
WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url
string DeprecatedisInPlace
boolean DeprecatedisMainFrame
boolean DeprecatedframeProcessId
Integer DeprecatedframeRoutingId
Integer Deprecated
Emitted when a user or the page wants to start navigation on the main frame. It can happen when the window.location
object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with APIs like webContents.loadURL
and webContents.back
.
It is also not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash
. Use did-navigate-in-page
event for this purpose.
Calling event.preventDefault()
will prevent the navigation.
Event: 'will-frame-navigate'
Возвращает:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalse
for this event.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain - The frame to be navigated.initiator
WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
Emitted when a user or the page wants to start navigation in any frame. It can happen when the window.location
object is changed or a user clicks a link in the page.
Unlike will-navigate
, will-frame-navigate
is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, isMainFrame
will be true
.
This event will not emit when the navigation is started programmatically with APIs like webContents.loadURL
and webContents.back
.
It is also not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash
. Use did-navigate-in-page
event for this purpose.
Calling event.preventDefault()
will prevent the navigation.