Electron's webview
tag is based on Chromium's webview
, which
is undergoing dramatic architectural changes. This impacts the stability of webviews
,
including rendering, navigation, and event routing. We currently recommend to not
use the webview
tag and to consider alternatives, like iframe
, Electron's BrowserView
,
or an architecture that avoids embedded content altogether.
By default the webview
tag is disabled in Electron >= 5. You need to enable the tag by
setting the webviewTag
webPreferences option when constructing your BrowserWindow
. For
more information see the BrowserWindow constructor docs.
Display external web content in an isolated frame and process.
Process: Renderer
This class is not exported from the 'electron'
module. It is only available as a return value of other methods in the Electron API.
Use the webview
tag to embed 'guest' content (such as web pages) in your
Electron app. The guest content is contained within the webview
container.
An embedded page within your app controls how the guest content is laid out and
rendered.
Unlike an iframe
, the webview
runs in a separate process than your
app. It doesn't have the same permissions as your web page and all interactions
between your app and embedded content will be asynchronous. This keeps your app
safe from the embedded content. Note: Most methods called on the
webview from the host page require a synchronous call to the main process.
To embed a web page in your app, add the webview
tag to your app's embedder
page (this is the app page that will display the guest content). In its simplest
form, the webview
tag includes the src
of the web page and css styles that
control the appearance of the webview
container:
<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>
If you want to control the guest content in any way, you can write JavaScript
that listens for webview
events and responds to those events using the
webview
methods. Here's sample code with two event listeners: one that listens
for the web page to start loading, the other for the web page to stop loading,
and displays a "loading..." message during the load time:
<script>
onload = () => {
const webview = document.querySelector('webview')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
Under the hood webview
is implemented with Out-of-Process iframes (OOPIFs).
The webview
tag is essentially a custom element using shadow DOM to wrap an
iframe
element inside it.
So the behavior of webview
is very similar to a cross-domain iframe
, as
examples:
- When clicking into a
webview
, the page focus will move from the embedder frame towebview
. - You can not add keyboard, mouse, and scroll event listeners to
webview
. - All reactions between the embedder frame and
webview
are asynchronous.
Please note that the webview
tag's style uses display:flex;
internally to
ensure the child iframe
element fills the full height and width of its webview
container when used with traditional and flexbox layouts. Please do not
overwrite the default display:flex;
CSS property, unless specifying
display:inline-flex;
for inline layout.
The webview
tag has the following attributes:
<webview src="https://www.github.com/"></webview>
A String
representing the visible URL. Writing to this attribute initiates top-level
navigation.
Assigning src
its own value will reload the current page.
The src
attribute can also accept data URLs, such as
data:text/plain,Hello, world!
.
<webview src="http://www.google.com/" nodeintegration></webview>
A Boolean
. When this attribute is present the guest page in webview
will have node
integration and can use node APIs like require
and process
to access low
level system resources. Node integration is disabled by default in the guest
page.
<webview src="http://www.google.com/" nodeintegrationinsubframes></webview>
A Boolean
for the experimental option for enabling NodeJS support in sub-frames such as iframes
inside the webview
. All your preloads will load for every iframe, you can
use process.isMainFrame
to determine if you are in the main frame or not.
This option is disabled by default in the guest page.
<webview src="https://www.github.com/" plugins></webview>
A Boolean
. When this attribute is present the guest page in webview
will be able to use
browser plugins. Plugins are disabled by default.
<!-- from a file -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- or if you want to load from an asar archive -->
<webview src="https://www.github.com/" preload="./app.asar/test.js"></webview>
A String
that specifies a script that will be loaded before other scripts run in the guest
page. The protocol of script's URL must be file:
(even when using asar:
archives) because
it will be loaded by Node's require
under the hood, which treats asar:
archives as virtual
directories.
When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing.
Note: This option will appear as preloadURL
(not preload
) in
the webPreferences
specified to the will-attach-webview
event.
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
A String
that sets the referrer URL for the guest page.
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
A String
that sets the user agent for the guest page before the page is navigated to. Once the
page is loaded, use the setUserAgent
method to change the user agent.
<webview src="https://www.github.com/" disablewebsecurity></webview>
A Boolean
. When this attribute is present the guest page will have web security disabled.
Web security is enabled by default.
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>
A String
that sets the session used by the page. If partition
starts with persist:
, the
page will use a persistent session available to all pages in the app with the
same partition
. if there is no persist:
prefix, the page will use an
in-memory session. By assigning the same partition
, multiple pages can share
the same session. If the partition
is unset then default session of the app
will be used.
This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception.
<webview src="https://www.github.com/" allowpopups></webview>
A Boolean
. When this attribute is present the guest page will be allowed to open new
windows. Popups are disabled by default.
<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>
A String
which is a comma separated list of strings which specifies the web preferences to be set on the webview.
The full list of supported preference strings can be found in BrowserWindow.
The string follows the same format as the features string in window.open
.
A name by itself is given a true
boolean value.
A preference can be set to another value by including an =
, followed by the value.
Special values yes
and 1
are interpreted as true
, while no
and 0
are interpreted as false
.
<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
A String
which is a list of strings which specifies the blink features to be enabled separated by ,
.
The full list of supported feature strings can be found in the
RuntimeEnabledFeatures.json5 file.
<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
A String
which is a list of strings which specifies the blink features to be disabled separated by ,
.
The full list of supported feature strings can be found in the
RuntimeEnabledFeatures.json5 file.
The webview
tag has the following methods:
Note: The webview element must be loaded before using the methods.
Example
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
url
URLoptions
Object (optional)httpReferrer
(String | Referrer) (optional) - An HTTP Referrer url.userAgent
String (optional) - A user agent originating the request.extraHeaders
String (optional) - Extra headers separated by "\n"postData
(UploadRawData | UploadFile)[] (optional)baseURLForDataURL
String (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specifiedurl
is a data url and needs to load other files.
Returns Promise<void>
- The promise will resolve when the page has finished loading
(see did-finish-load
), and rejects
if the page fails to load (see
did-fail-load
).
Loads the url
in the webview, the url
must contain the protocol prefix,
e.g. the http://
or file://
.
url
String
Initiates a download of the resource at url
without navigating.
Returns String
- The URL of guest page.
Returns String
- The title of guest page.
Returns Boolean
- Whether guest page is still loading resources.
Returns Boolean
- Whether the main frame (and not just iframes or frames within it) is
still loading.
Returns Boolean
- Whether the guest page is waiting for a first-response for the
main resource of the page.
Stops any pending navigation.
Reloads the guest page.
Reloads the guest page and ignores cache.
Returns Boolean
- Whether the guest page can go back.
Returns Boolean
- Whether the guest page can go forward.
offset
Integer
Returns Boolean
- Whether the guest page can go to offset
.
Clears the navigation history.
Makes the guest page go back.
Makes the guest page go forward.
index
Integer
Navigates to the specified absolute index.
offset
Integer
Navigates to the specified offset from the "current entry".
Returns Boolean
- Whether the renderer process has crashed.
userAgent
String
Overrides the user agent for the guest page.
Returns String
- The user agent for guest page.
css
String
Returns Promise<String>
- A promise that resolves with a key for the inserted
CSS that can later be used to remove the CSS via
<webview>.removeInsertedCSS(key)
.
Injects CSS into the current web page and returns a unique key for the inserted stylesheet.
key
String
Returns Promise<void>
- Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from <webview>.insertCSS(css)
.
code
StringuserGesture
Boolean (optional) - Defaultfalse
.
Returns Promise<any>
- A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates code
in page. If userGesture
is set, it will create the user
gesture context in the page. HTML APIs like requestFullScreen
, which require
user action, can take advantage of this option for automation.
Opens a DevTools window for guest page.
Closes the DevTools window of guest page.
Returns Boolean
- Whether guest page has a DevTools window attached.
Returns Boolean
- Whether DevTools window of guest page is focused.
x
Integery
Integer
Starts inspecting element at position (x
, y
) of guest page.
Opens the DevTools for the shared worker context present in the guest page.
Opens the DevTools for the service worker context present in the guest page.
muted
Boolean
Set guest page muted.
Returns Boolean
- Whether guest page has been muted.
Returns Boolean
- Whether audio is currently playing.
Executes editing command undo
in page.
Executes editing command redo
in page.
Executes editing command cut
in page.
Executes editing command copy
in page.
Executes editing command paste
in page.
Executes editing command pasteAndMatchStyle
in page.
Executes editing command delete
in page.
Executes editing command selectAll
in page.
Executes editing command unselect
in page.
text
String
Executes editing command replace
in page.
text
String
Executes editing command replaceMisspelling
in page.
text
String
Returns Promise<void>
Inserts text
to the focused element.
text
String - Content to be searched, must not be empty.options
Object (optional)forward
Boolean (optional) - Whether to search forward or backward, defaults totrue
.findNext
Boolean (optional) - Whether to begin a new text finding session with this request. Should betrue
for initial requests, andfalse
for follow-up requests. Defaults tofalse
.matchCase
Boolean (optional) - Whether search should be case-sensitive, defaults tofalse
.
Returns Integer
- The request id used for the request.
Starts a request to find all matches for the text
in the web page. The result of the request
can be obtained by subscribing to found-in-page
event.
action
String - Specifies the action to take place when ending<webview>.findInPage
request.clearSelection
- Clear the selection.keepSelection
- Translate the selection into a normal selection.activateSelection
- Focus and click the selection node.
Stops any findInPage
request for the webview
with the provided action
.
options
Object (optional)silent
Boolean (optional) - Don't ask user for print settings. Default isfalse
.printBackground
Boolean (optional) - Prints the background color and image of the web page. Default isfalse
.deviceName
String (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.color
Boolean (optional) - Set whether the printed web page will be in color or grayscale. Default istrue
.margins
Object (optional)marginType
String (optional) - Can bedefault
,none
,printableArea
, orcustom
. Ifcustom
is chosen, you will also need to specifytop
,bottom
,left
, andright
.top
Number (optional) - The top margin of the printed web page, in pixels.bottom
Number (optional) - The bottom margin of the printed web page, in pixels.left
Number (optional) - The left margin of the printed web page, in pixels.right
Number (optional) - The right margin of the printed web page, in pixels.
landscape
Boolean (optional) - Whether the web page should be printed in landscape mode. Default isfalse
.scaleFactor
Number (optional) - The scale factor of the web page.pagesPerSheet
Number (optional) - The number of pages to print per page sheet.collate
Boolean (optional) - Whether the web page should be collated.copies
Number (optional) - The number of copies of the web page to print.pageRanges
Object[] (optional) - The page range to print.from
Number - Index of the first page to print (0-based).to
Number - Index of the last page to print (inclusive) (0-based).
duplexMode
String (optional) - Set the duplex mode of the printed web page. Can besimplex
,shortEdge
, orlongEdge
.dpi
Record<string, number> (optional)horizontal
Number (optional) - The horizontal dpi.vertical
Number (optional) - The vertical dpi.
header
String (optional) - String to be printed as page header.footer
String (optional) - String to be printed as page footer.pageSize
String | Size (optional) - Specify page size of the printed document. Can beA3
,A4
,A5
,Legal
,Letter
,Tabloid
or an Object containingheight
.
Returns Promise<void>
Prints webview
's web page. Same as webContents.print([options])
.
options
ObjectheaderFooter
Record<string, string> (optional) - the header and footer for the PDF.title
String - The title for the PDF header.url
String - the url for the PDF footer.
landscape
Boolean (optional) -true
for landscape,false
for portrait.marginsType
Integer (optional) - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. andwidth
in microns.scaleFactor
Number (optional) - The scale factor of the web page. Can range from 0 to 100.pageRanges
Record<string, number> (optional) - The page range to print. On macOS, only the first range is honored.from
Number - Index of the first page to print (0-based).to
Number - Index of the last page to print (inclusive) (0-based).
pageSize
String | Size (optional) - Specify page size of the generated PDF. Can beA3
,A4
,A5
,Legal
,Letter
,Tabloid
or an Object containingheight
printBackground
Boolean (optional) - Whether to print CSS backgrounds.printSelectionOnly
Boolean (optional) - Whether to print selection only.
Returns Promise<Uint8Array>
- Resolves with the generated PDF data.
Prints webview
's web page as PDF, Same as webContents.printToPDF(options)
.
rect
Rectangle (optional) - The area of the page to be captured.
Returns Promise<NativeImage>
- Resolves with a NativeImage
Captures a snapshot of the page within rect
. Omitting rect
will capture the whole visible page.
channel
String...args
any[]
Returns Promise<void>
Send an asynchronous message to renderer process via channel
, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the channel
event with the ipcRenderer
module.
See webContents.send for examples.
frameId
[number, number] -[processId, frameId]
channel
String...args
any[]
Returns Promise<void>
Send an asynchronous message to renderer process via channel
, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the channel
event with the ipcRenderer
module.
See webContents.sendToFrame for examples.
Returns Promise<void>
Sends an input event
to the page.
See webContents.sendInputEvent
for detailed description of event
object.
factor
Number - Zoom factor.
Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.
level
Number - Zoom level.
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
scale := 1.2 ^ level
.
NOTE: The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. Differentiating the window URLs will make zoom work per-window.
Returns Number
- the current zoom factor.
Returns Number
- the current zoom level.
minimumLevel
NumbermaximumLevel
Number
Returns Promise<void>
Sets the maximum and minimum pinch-to-zoom level.
Shows pop-up dictionary that searches the selected word on the page.
Returns Number
- The WebContents ID of this webview
.
The following DOM events are available to the webview
tag:
Returns:
url
StringisMainFrame
Boolean
Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads.
Fired when the navigation is done, i.e. the spinner of the tab will stop
spinning, and the onload
event is dispatched.
Returns:
errorCode
IntegererrorDescription
StringvalidatedURL
StringisMainFrame
Boolean
This event is like did-finish-load
, but fired when the load failed or was
cancelled, e.g. window.stop()
is invoked.
Returns:
isMainFrame
Boolean
Fired when a frame has done navigation.
Corresponds to the points in time when the spinner of the tab starts spinning.
Corresponds to the points in time when the spinner of the tab stops spinning.
Fired when attached to the embedder web contents.
Fired when document in the given frame is loaded.
Returns:
title
StringexplicitSet
Boolean
Fired when page title is set during navigation. explicitSet
is false when
title is synthesized from file url.
Returns:
favicons
String[] - Array of URLs.
Fired when page receives favicon urls.
Fired when page enters fullscreen triggered by HTML API.
Fired when page leaves fullscreen triggered by HTML API.
Returns:
level
Integer - The log level, from 0 to 3. In order it matchesverbose
,info
,warning
anderror
.message
String - The actual console messageline
Integer - The line number of the source that triggered this console messagesourceId
String
Fired when the guest window logs a console message.
The following example code forwards all log messages to the embedder's console without regard for log level or other properties.
const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
})
Returns:
result
ObjectrequestId
IntegeractiveMatchOrdinal
Integer - Position of the active match.matches
Integer - Number of Matches.selectionArea
Rectangle - Coordinates of first match region.finalUpdate
Boolean
Fired when a result is available for
webview.findInPage
request.
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test')
console.log(requestId)
Returns:
url
StringframeName
Stringdisposition
String - Can bedefault
,foreground-tab
,background-tab
,new-window
,save-to-disk
andother
.options
BrowserWindowConstructorOptions - The options which should be used for creating the newBrowserWindow
.
Fired when the guest page attempts to open a new browser window.
The following example code opens the new url in system's default browser.
const { shell } = require('electron')
const webview = document.querySelector('webview')
webview.addEventListener('new-window', async (e) => {
const protocol = (new URL(e.url)).protocol
if (protocol === 'http:' || protocol === 'https:') {
await shell.openExternal(e.url)
}
})
Returns:
url
String
Emitted when a user or the page wants to start navigation. 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 <webview>.loadURL
and <webview>.back
.
It is also not emitted during in-page navigation, such as clicking anchor links
or updating the window.location.hash
. Use did-navigate-in-page
event for
this purpose.
Calling event.preventDefault()
does NOT have any effect.
Returns:
url
StringisInPlace
BooleanisMainFrame
BooleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame (including main) starts navigating. isInPlace
will be
true
for in-page navigations.
Returns:
url
StringisInPlace
BooleanisMainFrame
BooleanframeProcessId
IntegerframeRoutingId
Integer
Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
Returns:
url
String
Emitted when a navigation is done.
This event is 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.
Returns:
url
StringhttpResponseCode
Integer - -1 for non HTTP navigationshttpStatusText
String - empty for non HTTP navigations,isMainFrame
BooleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame navigation is done.
This event is 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.
Returns:
isMainFrame
Booleanurl
String
Emitted when an in-page navigation happened.
When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM hashchange
event is triggered.
Fired when the guest page attempts to close itself.
The following example code navigates the webview
to about:blank
when the
guest attempts to close itself.
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})
Returns:
frameId
[number, number] - pair of[processId, frameId]
.channel
Stringargs
any[]
Fired when the guest page has sent an asynchronous message to embedder page.
With sendToHost
method and ipc-message
event you can communicate
between guest page and embedder page:
// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
Fired when the renderer process is crashed.
Returns:
name
Stringversion
String
Fired when a plugin process is crashed.
Fired when the WebContents is destroyed.
Emitted when media starts playing.
Emitted when media is paused or done playing.
Returns:
themeColor
String
Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
<meta name='theme-color' content='#ff0000'>
Returns:
url
String
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
Emitted when DevTools is opened.
Emitted when DevTools is closed.
Emitted when DevTools is focused / opened.
Returns:
params
Objectx
Integer - x coordinate.y
Integer - y coordinate.linkURL
String - URL of the link that encloses the node the context menu was invoked on.linkText
String - Text associated with the link. May be an empty string if the contents of the link are an image.pageURL
String - URL of the top level page that the context menu was invoked on.frameURL
String - URL of the subframe that the context menu was invoked on.srcURL
String - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.mediaType
String - Type of the node the context menu was invoked on. Can benone
,image
,audio
,video
,canvas
,file
orplugin
.hasImageContents
Boolean - Whether the context menu was invoked on an image which has non-empty contents.isEditable
Boolean - Whether the context is editable.selectionText
String - Text of the selection that the context menu was invoked on.titleText
String - Title text of the selection that the context menu was invoked on.altText
String - Alt text of the selection that the context menu was invoked on.suggestedFilename
String - Suggested filename to be used when saving file through 'Save Link As' option of context menu.selectionRect
Rectangle - Rect representing the coordinates in the document space of the selection.selectionStartOffset
Number - Start position of the selection text.referrerPolicy
Referrer - The referrer policy of the frame on which the menu is invoked.misspelledWord
String - The misspelled word under the cursor, if any.dictionarySuggestions
String[] - An array of suggested words to show the user to replace themisspelledWord
. Only available if there is a misspelled word and spellchecker is enabled.frameCharset
String - The character encoding of the frame on which the menu was invoked.inputFieldType
String - If the context menu was invoked on an input field, the type of that field. Possible values arenone
,plainText
,password
,other
.spellcheckEnabled
Boolean - If the context is editable, whether or not spellchecking is enabled.menuSourceType
String - Input source that invoked the context menu. Can benone
,mouse
,keyboard
,touch
,touchMenu
,longPress
,longTap
,touchHandle
,stylus
,adjustSelection
, oradjustSelectionReset
.mediaFlags
Object - The flags for the media element the context menu was invoked on.inError
Boolean - Whether the media element has crashed.isPaused
Boolean - Whether the media element is paused.isMuted
Boolean - Whether the media element is muted.hasAudio
Boolean - Whether the media element has audio.isLooping
Boolean - Whether the media element is looping.isControlsVisible
Boolean - Whether the media element's controls are visible.canToggleControls
Boolean - Whether the media element's controls are toggleable.canPrint
Boolean - Whether the media element can be printed.canSave
Boolean - Whether or not the media element can be downloaded.canShowPictureInPicture
Boolean - Whether the media element can show picture-in-picture.isShowingPictureInPicture
Boolean - Whether the media element is currently showing picture-in-picture.canRotate
Boolean - Whether the media element can be rotated.canLoop
Boolean - Whether the media element can be looped.
editFlags
Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.canUndo
Boolean - Whether the renderer believes it can undo.canRedo
Boolean - Whether the renderer believes it can redo.canCut
Boolean - Whether the renderer believes it can cut.canCopy
Boolean - Whether the renderer believes it can copy.canPaste
Boolean - Whether the renderer believes it can paste.canDelete
Boolean - Whether the renderer believes it can delete.canSelectAll
Boolean - Whether the renderer believes it can select all.canEditRichly
Boolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.