May 25, 2021 Electron
webContents
is
an
event issuer
.
It is responsible for
rendering and controlling web pages and is
BrowserWindow
object.
An example
of
webContents
const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({width: 800, height: 1500});
win.loadURL("https://www.w3cschool.cn");
var webContents = win.webContents;
webContents
emits the following events:
When the navigation is complete, an event is
onload
event is completed.
Return:
event
Event
errorCode
Integer
errorDescription
String
validatedURL
String
This event
is similar
did-finish-load
but is
issued when the load fails or cancels the load, for
window.stop()
ends.
A complete list of error
codes and their meanings can be
found here.
Return:
event
Event
isMainFrame
Boolean
An event is issued when a frame navigation is complete.
When tab's spinner starts spinning.
When tab's spinner ends spinning.
Return:
event
Event
status
Boolean
newURL
String
originalURL
String
httpResponseCode
Integer
requestMethod
String
referrer
String
headers
Object
An event is issued when more information about the requested resource is available.
status
Status
identifies the socket link to download the resource.
Return:
event
Event
oldURL
String
newURL
String
isMainFrame
Boolean
httpResponseCode
Integer
requestMethod
String
referrer
String
headers
Object
An event is issued when a redirect is received when a resource is requested.
Return:
event
Event
The event is issued when the document in the specified frame is loaded.
Return:
event
Event
favicons
Array - Array of URLs
An event is sent when the page receives the icon url.
Return:
event
Event
url
String
frameName
String
disposition
String - can
default
,
foreground-tab
,
background-tab
,
new-window
with
other
.
options
Object -
The parameters used to create a new
BrowserWindow
An event is emitted when the page requests to open the specified url window.
This can
be a request made
window.open
or an external
<a target='_blank'>
.
url
BrowserWindow
is created.
Calling
event.preventDefault()
to prevent windows from opening.
Return:
event
Event
url
String
An event is emitted when the user or page wants to start navigating.
It can
occur when
window.location
object changes or the user clicks on a link in the page.
This event will not
webContents.loadURL
and
webContents.back
to start navigation programmatically.
It also does not jump within the page, for
example by clicking on an anchor link or
did-navigate-in-page
.
window.location.hash
Calling
event.preventDefault()
block navigation.
Return:
event
Event
url
String
An event is issued at the end of a navigation.
This event is not emitted when jumping within
a page, such as clicking on an anchor link or
did-navigate-in-page
window.location.hash
Return:
event
Event
url
String
An event is issued when in-page navigation occurs.
When in-page navigation occurs, the url of the page changes but does not jump out of the interface.
For example, when an anchor
link is clicked or the
hashchange
event of the DOM occurs.
An event is issued when the rendering process crashes.
Return:
event
Event
name
String
version
String
An event is issued when the plug-in process crashes.
An
webContents
are deleted.
Events are issued when the developer toolbar opens.
An event is issued when the developer toolbar is closed.
Issue events when the developer toolbar gets focus or opens.
Return:
event
Event
url
URL
error
String - The error code
certificate
Object
data
Buffer - PEM encoded data
issuerName
String
callback
Function
An event
is issued when
url
authentication certificate or url fails.
Use a
certificate-error
app
that is similar to the app
.
Return:
event
Event
url
URL
certificateList
[Objects]
data
Buffer - PEM encoded data
issuerName
String - Issuer's Common Name
callback
Function
An event is issued when a client certificate is requested.
Use a
select-client-certificate
app
event similar to the app
.
Return:
event
Event
request
Object
method
String
url
URL
referrer
URL
authInfo
Object
isProxy
Boolean
scheme
String
host
String
port
Integer
realm
String
callback
Function
Issue
webContents
want to do basic validation.
Use it
like
the
login
event of
app
.
Return:
event
Event
result
Object
requestId
Integer
finalUpdate
Boolean - Identify whether there are more values to view.
activeMatchOrdinal
Integer (optional) - Active matching location
matches
Integer (optional) - match quantity.
selectionArea
Object (optional) - coordinates the first matching position.
Issue
webContents.findInPage
for in-page lookups and find available worth it.
An event is issued when the media starts playing.
An event is issued when the media stops playing.
Events are issued when the subject color of the page. This is usually due to the introduction of a meta tag:
<meta name='theme-color' content='#ff0000'>
Return:
event
Event
type
String
image
NativeImage (optional)
scale
Float (optional)
An event is issued when the type of mouse changes. <
type
The parameter can be
default
,
crosshair
,
pointer
,
text
,
wait
,
help
,
e-resize
,
n-resize
,
ne-resize
,
nw-resize
,
s-resize
,
se-resize
,
sw-resize
,
w-resize
,
ns-resize
,
ew-resize
,
nesw-resize
,
nwse-resize
,
col-resize
,
row-resize
,
m-panning
,
e-panning
,
n-panning
,
ne-panning
,
nw-panning
,
s-panning
,
se-panning
,
sw-panning
,
w-panning
,
move
,
vertical-text
,
cell
,
context-menu
,
alias
,
progress
,
nodrop
,
copy
,
none
,
not-allowed
,
zoom-in
,
zoom-out
,
grab
,
grabbing
,
custom
.
If
type
type
parameter value
custom
image
parameter controls the custom mouse picture in a
NativeImage
and
scale
controls the scale of the picture.
webContents
object has the following instance method:
webContents.loadURL(url[, options])
url
URL
options
Object (optional)
httpReferrer
String - A HTTP Referrer url.
userAgent
String - The user agent that generated the request
extraHeaders
String - Extra head separated by ''n'
Load url
in the
url
url
must
contain a protocol prefix,
http://
or
file://
.
If the load wants
to ignore the http cache,
pragma
header to achieve the goal.
const options = {"extraHeaders" : "pragma: no-cache\n"}
webContents.loadURL(url, options)
webContents.downloadURL(url)
url
URL
Initialize a
resource download
url
specified url without navigating the jump.
session
will-download
event is triggered.
webContents.getURL()
Returns the url of the current page.
var win = new BrowserWindow({width: 800, height: 600});
win.loadURL("http://github.com");
var currentURL = win.webContents.getURL();
webContents.getTitle()
Returns the title of the current page.
webContents.isLoading()
Returns a Boolean value that identifies whether the current page is loading.
webContents.isWaitingForResponse()
Returns a Boolean value that identifies whether the current page is waiting for the first response from the primary resource.
webContents.stop()
Stop also for starting navigation.
webContents.reload()
Overload the current page.
webContents.reloadIgnoringCache()
Overload the current page and ignore the cache.
webContents.canGoBack()
Return a Boolean value that identifies whether the browser can go back to the previous page.
webContents.canGoForward()
Return a Boolean value that identifies whether the browser can go to the next page.
webContents.canGoToOffset(offset)
offset
Integer
Returns a Boolean value that
identifies whether the browser can go to
offset
of the specified offset.
webContents.clearHistory()
Clear navigation history.
webContents.goBack()
Let the browser fall back to the previous page.
webContents.goForward()
Let the browser go back to the next page.
webContents.goToIndex(index)
index
Integer
Let the browser
go back to
index
of the specified index.
webContents.goToOffset(offset)
offset
Integer
Navigate to the offset position page relative to the current page.
webContents.isCrashed()
Whether the rendering process crashes.
webContents.setUserAgent(userAgent)
userAgent
String
Rewrite this page for user agents.
webContents.getUserAgent()
Return a
String
the user agent information on this page.
webContents.insertCSS(css)
css
String
Insert css for the current page.
webContents.executeJavaScript(code[, userGesture, callback])
code
String
userGesture
Boolean (optional)
callback
Function (optional) - Callback function called after script execution is complete.
result
Evaluate
the page
代码
.
Some HTML APIs in
the browser window, such as
requestFullScreen
can only be requested by user gestures.
Setting
userGesture
true
remove this restriction.
win.webContents.executeJavaScript('\
$(".skey").focus();\
');
webContents.setAudioMuted(muted)
muted
Boolean
Slow down the playback of the current audio as well.
webContents.isAudioMuted()
Returns a Boolean value that identifies whether the current page slows down audio playback.
webContents.undo()
Perform the page's edit command
undo
.
webContents.redo()
Execute the page's editing
redo
.
webContents.cut()
Execute the page's edit command
cut
.
webContents.copy()
Copy the edit
command for the
copy
.
webContents.paste()
Execute the page's edit command
paste
.
webContents.pasteAndMatchStyle()
Execute the page's
pasteAndMatchStyle
.
webContents.delete()
Execute the page's editing command
delete
.
webContents.selectAll()
Execute the page's edit command
selectAll
.
webContents.unselect()
Performs the
edit command of
unselect
.
webContents.replace(text)
text
String
Execute the page's edit command
replace
.
webContents.replaceMisspelling(text)
text
String
Execute the page's
replaceMisspelling
.
webContents.insertText(text)
text
String
Insert
text
the element that gets the focus.
webContents.findInPage(text[, options])
text
String - Find content, cannot be empty.
options
Object (optional)
forward
Boolean - Whether to look
forward or back, the default is
true
.
findNext
Boolean - Whether the current operation is the
first or next lookup, the default is
false
.
matchCase
Boolean - Find out if
case sensitive, the default is
false
.
wordStart
Boolean - Whether to look only in the initials.
The
default is
false
.
medialCapitalAsWordStart
Boolean -
Whether or not to combine
wordStart
if the match is the beginning of a capital letter, followed by a lowercase letter or no letter, then accept the match in the word.
Several other synthetic word matches
are accepted, the default being
false
.
Make a request, look
for all
text
the web page, and return an
Integer
to indicate the request Id for the request. The result of
this request can be
found-in-page
event.
webContents.stopFindInPage(action)
action
String - Specifies a
behavior to replace
webContents.findInPage
request.
clearSelection
- transforms into a normal selection.
keepSelection
- Clear selection.
activateSelection
- Get the focus and click on selection node.
Use the
given
action
to stop any
findInPage requests
findInPage
webContents
webContents.on('found-in-page', function(event, result) {
if (result.finalUpdate)
webContents.stopFindInPage("clearSelection");
});
const requestId = webContents.findInPage("api");
webContents.hasServiceWorker(callback)
callback
Function
Check to see if any ServiceWorker is registered
and return a Boolean value as the
callback
response.
webContents.unregisterServiceWorker(callback)
callback
Function
If any ServiceWorker exists, log off all and return a Boolean value that identifies the appropriate
callback
when JS commits to execution or JS fails to execute
.
webContents.print([options])
options
Object (optional)
silent
Boolean - You do not need to request the user's print settings.
The
default is
false
.
printBackground
Boolean - Print background and web page pictures.
The
default is
false
.
Print the page of the window.
When
silent
is set
false
Electron prints using the system's default printer and printing method.
Calling
window.print()
a Web page and
webContents.print({silent: false, printBackground: false})
have the same effect.
Note: In
Windows,
the print API
pdf.dll
.
If your app doesn't
use any printing, you
pdf.dll
pdf files to reduce the size of binary files.
webContents.printToPDF(options, callback)
options
Object
marginsType
Integer - Specify the use of margin type.
The default margin uses 0, no margin uses 1, minimizes margin use 2.
pageSize
String - specify the page size of the generated PDF file.
This
can be
A3
A4
A5
Legal
Letter
and
Tabloid
.
printBackground
Boolean - Whether to print css background.
printSelectionOnly
Boolean - Whether to print only the selected section.
landscape
Boolean -
Landscape is
true
portrait is
false
.
callback
Function
The page of the print window is pdf and uses chromium preview to print custom settings.
Callback
when
callback(error, data)
(error,
callback
data
Data
is
a
Buffer
contains the generated pdf data.
By default,
empty
options
{
marginsType: 0,
printBackground: false,
printSelectionOnly: false,
landscape: false
}
const BrowserWindow = require('electron').BrowserWindow;
const fs = require('fs');
var win = new BrowserWindow({width: 800, height: 600});
win.loadURL("https://www.w3cschool.cn");
win.webContents.on("did-finish-load", function() {
// Use default printing options
win.webContents.printToPDF({}, function(error, data) {
if (error) throw error;
fs.writeFile("/tmp/print.pdf", data, function(error) {
if (error)
throw error;
console.log("Write PDF successfully.");
})
})
});
webContents.addWorkSpace(path)
path
String
Add the specified path to the developer toolbar's workspace. You must use it after DevTools is created:
mainWindow.webContents.on('devtools-opened', function() {
mainWindow.webContents.addWorkSpace(__dirname);
});
webContents.removeWorkSpace(path)
path
String
Remove the specified path from the developer toolbar's workspace.
webContents.openDevTools([options])
options
Object (optional)
detach
Boolean - Open the developer toolbar in a new window
Open the developer toolbar.
webContents.closeDevTools()
Close the developer toolbar.
webContents.isDevToolsOpened()
Return boolean value, developer toolbar is open.
webContents.isDevToolsFocused()
Return boolean value, developer toolbar view whether to get focus.
webContents.toggleDevTools()
Toggles Developer Tools.
webContents.inspectElement(x, y)
x
Integer
y
Integer
Start
x
in ( x ,
y
) .
webContents.inspectServiceWorker()
Open the developer toolbar for the service worker context.
webContents.send(channel[, arg1][, arg2][, ...])
channel
String
arg
(optional)
You
can also send arbitrary parameters by sending asynchronous messages to the rendering process via
channel
Arguments should be serialized inside JSON and no functions or original chains have been included since then.
The rendering
process can process
ipcRenderer
channel
in on the channel.
Example, sending a message from the main process to the rendering process:
// 主进程.
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
window.loadURL('file://' + __dirname + '/index.html');
window.webContents.on('did-finish-load', function() {
window.webContents.send('ping', 'whoooooooh!');
});
});
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', function(event, message) {
console.log(message); // Prints "whoooooooh!"
});
</script>
</body>
</html>
webContents.enableDeviceEmulation(parameters)
parameters
Object, properties:
screenPosition
String - Specifies the
screen that needs to be simulated (default:
desktop
)
desktop
mobile
screenSize
Object - Set analog screen size (screenPosition s mobile)
width
Integer - Set up an analog screen width
height
Integer - Set up an analog screen height
viewPosition
Object - Place view on the screen
(screenPosition s mobile) (default:
{x: 0, y: 0}
)
x
Integer - Sets the x-axis in the upper left corner of the offset
y
Integer - Set the y-axis in the upper left corner of the offset
deviceScaleFactor
Integer - Set the device scale factor (default to
the original screen scale if 0) (default:
0
)
viewSize
Object - Set analog view size (empty means not overwritten)
width
Integer - Set up an analog view of the width
height
Integer - Set up simulated view height
fitToView
Boolean - If necessary, scale the analog view proportionally to fit the available space (default:
false
)
offset
Object - Simulated view offset in free space
(not in fit mode) (default:
{x: 0, y: 0}
)
x
Float - Sets the x-axis offset value relative to the upper left corner
y
Float - Sets the y-axis offset value relative to the upper left corner
scale
Float - Simulated view offset in free space
(not in fit view mode) (default:
1
)
Use a given parameter to turn on device simulation.
webContents.disableDeviceEmulation()
Turn
webContents.enableDeviceEmulation
webContents.sendInputEvent(event)
event
Object
type
String
(required)
-
Event types, which
can be
mouseDown
mouseUp
mouseEnter
mouseLeave
contextMenu
mouseWheel
mouseMove
keyDown
keyUp
,
char
.
modifiers
Array - Event modifiers array, which
can be
include
shift
control
alt
meta
isKeypad
isAutoRepeat
leftButtonDown
middleButtonDown
rightButtonDown
,
capsLock
,
numLock
,
left
,
right
.
Send an input
event
to the page
.
For keyboard events, the
event
has the following properties:
keyCode
String
(required)
- features that will be sent as a keyboard event. Key codes
Accelerator is
available
.
For mouse events, the
event
has the following properties:
x
Integer (
required
)
y
Integer (
required
)
button
String - button
press, can
be
left
middle
right
globalX
Integer
globalY
Integer
movementX
Integer
movementY
Integer
clickCount
Integer
For mouse wheel events, the
event
also has the following properties:
deltaX
Integer
deltaY
Integer
wheelTicksX
Integer
wheelTicksY
Integer
accelerationRatioX
Integer
accelerationRatioY
Integer
hasPreciseScrollingDeltas
Boolean
canScroll
Boolean
webContents.beginFrameSubscription(callback)
callback
Function
Start subscribing to submit events and capturing data frames,
and
when there is a commit event, callback is called callback
callback(frameBuffer)
callback
.
frameBuffer
a Buffer
Buffer
that is stored efficiently in the 32bit BGRA format, but the reality is that it depends on the byte order of the processor (most processors are in small-end order and, if it is in large-end-order processors, the data is in 32bit ARGB format).
webContents.endFrameSubscription()
Stop subscribing to frame submission events.
webContents.savePage(fullPath, saveType, callback)
fullPath
String - Full path to the file.
saveType
String - Specify the save type.
HTMLOnly
- Save html only.
HTMLComplete
- Save the entire page content.
MHTML
- Save the full html for MHTML.
callback
Function -
function(error) {}
.
error
Error
If the initialization of the save interface process is successful, return true.
win.loadURL('https://www.w3cschool.cn');
win.webContents.on('did-finish-load', function() {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', function(error) {
if (!error)
console.log("Save page successfully");
});
});
WebContents
also have the following properties:
webContents.session
Return
the session object
used by this
webContents
webContents.hostWebContents
Return
to
webContents
webContents
.
webContents.devToolsWebContents
Get
WebContents
this
WebContents
.
Note: Users
cannot save this object because its value
is
null
when the developer toolbar is closed
.
webContents.debugger
The debug API provides alternate transfers for remote debugging protocol.
try {
win.webContents.debugger.attach("1.1");
} catch(err) {
console.log("Debugger attach failed : ", err);
};
win.webContents.debugger.on('detach', function(event, reason) {
console.log("Debugger detached due to : ", reason);
});
win.webContents.debugger.on('message', function(event, method, params) {
if (method == "Network.requestWillBeSent") {
if (params.request.url == "https://www.w3cschool.cn")
win.webContents.debugger.detach();
}
})
win.webContents.debugger.sendCommand("Network.enable");
webContents.debugger.attach([protocolVersion])
protocolVersion
String (optional) - Request a debug protocol version.
Add
webContents
webContents.debugger.isAttached()
Returns a Boolean value
that identifies whether debugging
webContents
webContents.debugger.detach()
Remove
webContents
webContents.debugger.sendCommand(method[, commandParams, callback])
method
String - Method name, which should be defined by the remote debug protocol.
commandParams
Object (optional) - The request parameter is the JSON object.
callback
Function (optional) - Response
error
Object - Error message, identity command failed.
result
Object - The reply is described in the remote debug protocol by a command defined by the 'returns' property.
Send a set command to the debugging target.
event
Event
reason
String - Split Debugger Reason.
An event is issued at the end of the debugging session.
This
webContents
are closed
webContents
request the developer toolbar.
event
Event
method
String - Method name.
params
Object - Event parameters defined by the 'parameters' property in the remote debugging protocol.
Issued whenever the debug target emits an event.