May 25, 2021 Electron
Use
webview
tab to embed 'guest' content , such as web pages , into your Electron app. Guest content is included
webview
container.
A page embedded in your app controls how the content is laid out and expressed.
Unlike
iframe
webview
your app run different processes. I
t does not have permission to render processes, and the interaction between the app and the embedded content is all asynchronous.
Because it can ensure that the security of the application is not affected by embedded content.
Embed a web page into your app and first add
webview
tab to your app to embed page .
In one of the
webview
it contains the file path of the web page and a css style that controls how the
webview
container presents:
<webview id="foo" src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" style="display:inline-block; width:640px; height:480px"></webview>
If you want to control guest content at any time, you can add JavaScript scripts to
webview
webview
method to respond. H
ere are two examples of event monitoring: one listening to the web page ready to load, the other listening to the web page to stop loading, and displaying a "loading..." at load time.
Information:
<script>
onload = function() {
var webview = document.getElementById("foo");
var indicator = document.querySelector(".indicator");
var loadstart = function() {
indicator.innerText = "loading...";
}
var loadstop = function() {
indicator.innerText = "";
}
webview.addEventListener("did-start-loading", loadstart);
webview.addEventListener("did-stop-loading", loadstop);
}
</script>
webview
tag has some properties:
src
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></webview>
Add an available url as the initial value of this property to the top navigation.
If you add the src of the current page, the current page will be loaded.
src
also fill in data urls, such
data:text/plain,Hello, world!
.
autosize
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" autosize="on" minwidth="576" minheight="432"></webview>
If the value of this property is "on" ,
webview
container will adapt the values of
minwidth
,
minheight
,
maxwidth
,
maxheight
between them according to the properties . T
his constraint will only work when
autosize
is turned on.
When
autosize
on, the size of the
webview
container can only be between the four property values above.
nodeintegration
<webview src="http://www.google.com/" rel="external nofollow" nodeintegration></webview>
If this property is set, the guest page
webview
consolidates node and has resources that can use the underlying system, such
require
and
process
.
plugins
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" plugins></webview>
If the value of this property is "on", the guest page in the
webview
can use the browser plug-in.
preload
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" preload="./test.js"></webview>
Preload a specified script before other scripts in the guest page are executed.
The url of the preloaded script must be
file:
as
asar:
it is loaded in the guest page
require
command.
If the guest page does not integrate node, the script will attempt to use the real Node APIs, but when the script is executed, the global object previously inserted by node will be deleted.
httpreferrer
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" httpreferrer="http://cheng.guru"></webview>
Set the referrer URL for the guest page.
useragent
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
Set up a user agent for the guest page before it loads.
If the page is already loaded, you
setUserAgent
to change the user agent.
disablewebsecurity
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" disablewebsecurity></webview>
If the value of this property is "on", guest page disables web security control.
<webview src="https://github.com" rel="external nofollow" partition="persist:github"></webview>
<webview src="http://electron.atom.io" rel="external nofollow" partition="electron"></webview>
Set up session for page. I
f the initial value
partition
this page will apply the same consistent session to all pagees in the app. I
f
persist:
prefix, this page will use a historical session. B
y assigning the
partition
all page can share the same session.
If
partition
is not set, the app will use the default session.
This value can only be modified before the first rendering process, after which the modification is invalid and throws a DOM exception.
allowpopups
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" allowpopups></webview>
If the value of this property is "on", guest page is allowed to open a new window.
blinkfeatures
<webview src="https://www.github.com/" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" blinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
The value of this property is a comma-separated list whose value specifies that the attribute is enabled. You can find the full support feature from the setFeatureEnabledFromString function.
webview
method collection:
Note: The webview element must be loaded before these methods can be used.
For example
webview.addEventListener("dom-ready", function() {
webview.openDevTools();
});
<webview>.loadURL(url[, options])
url
Url
options
Object (optional)
httpReferrer
String - an http type url.
userAgent
String - The user agent used to initiate the request.
extraHeaders
String - Extraheaders, separated by the ""
Load the url in
url
url
must contain a prefix for the
http://
or
file://
.
<webview>.getURL()
Return url from guest page.
<webview>.getTitle()
Return title from guest page.
<webview>.isLoading()
Returns whether a guest page is still loading the boolean value of the resource.
<webview>.isWaitingForResponse()
Returns a guest page whether the Boolean value is waiting for the page's primary resource to respond.
<webview>.stop()
Stop rendering.
<webview>.reload()
Reload guest page.
<webview>.reloadIgnoringCache()
Ignore the cache and reload the guest page.
<webview>.canGoBack()
Returns whether a guest page can fall back to the Boolean value.
<webview>.canGoForward()
Returns a guest page whether the Boolean value can advance.
<webview>.canGoToOffset(offset)
offset
Integer
Returns whether a guest page can advance to
offset
Boolean value.
<webview>.clearHistory()
Clear navigation history.
<webview>.goBack()
Guest page fallback.
<webview>.goForward()
Guest page forward.
<webview>.goToIndex(index)
index
Integer
Guest page navigates to the specified absolute location.
<webview>.goToOffset(offset)
offset
Integer
Guest page navigates to the specified relative location.
<webview>.isCrashed()
Returns a Boolean value of whether the rendering process crashed.
<webview>.setUserAgent(userAgent)
userAgent
String
Reset the user agent.
<webview>.getUserAgent()
Returns the user agent name and returns the
String
.
<webview>.insertCSS(css)
css
String
Insert css.
<webview>.executeJavaScript(code, userGesture, callback)
code
String
userGesture
Boolean - default
false
.
callback
Function (optional) - callback function.
result
Evaluate
code
and if
userGesture
is true, it will create user gestures in this page.
HTML APIs, such as
requestFullScreen
which require a user response, will be automatically optimized through this parameter.
<webview>.openDevTools()
Open the development tool debugging window for guest page.
<webview>.closeDevTools()
Close the development tool debugging window for guest page.
<webview>.isDevToolsOpened()
Returns whether a guest page opens the Boolean value of the development tool debug window.
<webview>.isDevToolsFocused()
Returns whether a guest page focuses on the Boolean value of the development tool debug window.
<webview>.inspectElement(x, y)
x
Integer
y
Integer
Start checking the element of
x
at the ( x ,
y
) position.
<webview>.inspectServiceWorker()
Open development tools for service personnel in guest page.
<webview>.setAudioMuted(muted)
muted
Boolean sets guest page smooth (muted).
<webview>.isAudioMuted()
Returns whether a guest page is a smooth Boolean value.
<webview>.undo()
Edit in page to execute the
undo
command.
<webview>.redo()
Edit in page to execute the
redo
command.
<webview>.cut()
Edit and execute the cut command
cut
<webview>.copy()
Edit in page to execute the
copy
command.
<webview>.paste()
Edit in page to execute
paste
command.
<webview>.pasteAndMatchStyle()
Edit and execute
pasteAndMatchStyle
<webview>.delete()
Edit in page to execute the
delete
command.
<webview>.selectAll()
Edit in page to execute the
selectAll
command.
<webview>.unselect()
Edit in page to execute
unselect
command.
<webview>.replace(text)
text
String
Edit in page to execute the
replace
command.
<webview>.replaceMisspelling(text)
text
String
Edit in page to execute
replaceMisspelling
command.
<webview>.insertText(text)
text
String
Insert text.
<webview>.findInPage(text[, options])
text
String - Search for content that cannot be empty.
options
Object (optional)
forward
Boolean - Forward or back, true
true
.
findNext
Boolean - Whether to look for the first result, the default is
false
.
matchCase
Boolean - Is case sensitive, the default is
false
.
wordStart
B
oolean - Whether to look for only the initials.
The default is
false
.
medialCapitalAsWordStart
B
oolean - When working
wordStart
accept a match in a text that requires a match to start with a capital letter followed by a lowercase letter or no letter.
Some other word internal matches can be accepted, with
false
.
Make a request to find all the matching
text
the page and
Integer
represent the request Id used for this request.
The result of this request can be
found-in-page
event.
<webview>.stopFindInPage(action)
action
String - Specifies an action to replace the
<webview>.findInPage
request.
clearSelection
- transforms into a normal selection.
keepSelection
- Clear selection.
activateSelection
- Focus and click on selection node.
Use
action
to
findInPage
<webview>.print([options])
Print out
webview
of the webview.
Similar
webContents.print([options])
.
<webview>.printToPDF(options, callback)
Print out the web page
webview
in pdf format.
Similar
webContents.printToPDF(options, callback)
.
<webview>.send(channel[, arg1][, arg2][, ...])
channel
String
arg
(optional)
You can also send arbitrary parameters by sending an asynchronous message to the rendering process via
channel
The rendering process controls the message by listening to channel events
channel
ipcRenderer
module.
Example webContents.send .
<webview>.sendInputEvent(event)
event
Object
Send input events to page.
View
webContents.sendInputEvent's trusted
event
objects.
<webview>.getWebContents()
Return to
webview
associated with this webview
.
webview
use the following DOM events:
Return:
url
String
isMainFrame
Boolean
Load complete trigger. This document contains the navigation of the current document and the subfringed document load, but does not contain asynchronous resource loading.
Triggered when the navigation load is complete, that is, tab's spinner stops spinner and loads event processing.
Returns:
errorCode
Integer
errorDescription
String
validatedURL
String
Similar
did-finish-load
failure or cancellation is triggered, for example by
window.stop()
.
Return:
isMainFrame
Boolean
Triggered when a frame completes loading.
Triggered when loading begins.
Triggered when the load is stopped.
Return:
status
Boolean
newURL
String
originalURL
String
httpResponseCode
Integer
requestMethod
String
referrer
String
headers
Object
Triggered when return details are obtained.
status
the socket connection to download the resource.
Return:
oldURL
String
newURL
String
isMainFrame
Boolean
Triggered when the redirect request resource is received.
Triggered when the specified frame document is loaded.
Return:
title
String
explicitSet
Boolean
Triggered when the page title in the navigation is set.
ExplicitSet is false when the title is
explicitSet
through the document path.
Return:
favicons
Array - Array of URLs.
Triggered when page receives icon url.
Triggered when the interface is brought into full screen through the HTML API.
Triggered when the interface exits full screen via HTML API.
Return:
level
Integer
message
String
line
Integer
sourceId
String
Triggered when the client outputs console information.
The following sample code outputs all the information to the built-in console without taking into account the output level and other properties.
webview.addEventListener('console-message', function(e) {
console.log('Guest page logged a message:', e.message);
});
Return:
result
Object
requestId
Integer
finalUpdate
Boolean - Indicates whether there are more responses below.
activeMatchOrdinal
Integer (optional) - Active matching location
matches
Integer (optional) - Match quantity.
selectionArea
Object (optional) - Consolidate the first matching domain.
Triggered
webview.findInPage
result is valid.
webview.addEventListener('found-in-page', function(e) {
if (e.result.finalUpdate)
webview.stopFindInPage("keepSelection");
});
const rquestId = webview.findInPage("test");
Return:
url
String
frameName
String
disposition
String - can
default
foreground-tab
background-tab
new-window
and
other
.
options
Object - The parameter should be used to create
BrowserWindow
.
Triggered when guest page tries to open a new browser window.
The following sample code opens a new url in the system default browser.
webview.addEventListener('new-window', function(e) {
require('electron').shell.openExternal(e.url);
});
Return:
url
String
Triggered when the user or page tries to start navigation.
It can be
window.location
changes or when the user clicks on the connection.
This event does not fire when you start navigating programmatically with APIS, such as
<webview>.loadURL
and
<webview>.back
.
Navigating jumps within the page will also not trigger this event back, such as clicking on an anchor link or updating
window.location.hash
. .
did-navigate-in-page
to implement in-page jump events.
Using
event.preventDefault()
of little use.
Return:
url
String
Triggered when navigation is over.
Navigating jumps within the page will also not trigger this event back, such as clicking on an anchor link or updating
window.location.hash
. .
did-navigate-in-page
to implement in-page jump events.
Return:
url
String
Triggered when in-page navigation occurs. W
hen industry navigation occurs, the page url changes, but does not jump out of the page .
For example, triggered when an anchor link is
hashchange
event occurs.
Trigger when guest page tries to close itself.
The following sample code indicates that the navigation connection will be changed to
about:blank
when the client tries to shut itself down
.
webview.addEventListener('close', function() {
webview.src = 'about:blank';
});
Return:
channel
String
args
Array
Triggers when guest page sends an asynchronous message to the embedded page.
You can
sendToHost
ipc-message
event to communicate between the guest page and the embedded page:
// In embedder page.
webview.addEventListener('ipc-message', function(event) {
console.log(event.channel);
// Prints "pong"
});
webview.send('ping');
// In guest page.
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('ping', function() {
ipcRenderer.sendToHost('pong');
});
Triggered when the rendering process crashes.
Triggered when the GPU process crashes.
Return:
name
String
version
String
Triggered when the plug-in process crashes.
Triggered when the interface content is destroyed.
Trigger when the media is ready to play.
Trigger when the media pauses or plays.
Triggered when the main color of the page changes. This is common when using meta tags:
<meta name='theme-color' content='#ff0000'>
Trigger when the developer tool is open.
Trigger when the developer tool is closed.
Trigger when the developer tool gets the focus.