Skip to content

WebContents ​

WebContents represents the web page inside a WebView. Loading URLs, going back and forward, observing the loading process, running scripts in the page, and exchanging messages with the page all happen on it.

WebView handles the view itself: position, size, showing and hiding. WebContents handles the web page:

TaskUseExample
Change position and sizeWebViewweb.frame = …, or constraints
Show, hide, opacityWebViewweb.isHidden = true
Rounded corners, borderWebViewweb.layer.cornerRadius = 12
Load a URL, go back and forwardWebContentsweb.webContents.loadURL(…)
Observe the loading processWebContentsweb.webContents.addEventListener(…)

Inheritance: EventTarget → WebContents

For how to display web pages, handle load failures, and restrict navigation, see the guide Displaying web pages; for exchanging messages with the page, see Messaging between a web page and the app.

Constructor ​

It can't be created with new: new WebContents() throws TypeError: Illegal constructor: WebContents is created by the runtime, not by new. It is created together with the WebView, and you get it from webView.webContents.

Instance properties ​

PropertyDescription
navigationHistory read-onlyBack and forward
ipc read-onlyAnswers requests the page sends with ipcRenderer.invoke
session read-onlyThe storage partition this page's data lives in

Instance methods ​

Loading and navigation:

MethodDescription
loadURL()Loads a URL
loadFile()Loads a local web page file
stop()Stops the load in progress
reload()Reloads the current URL

Reading the page's state:

MethodDescription
getURL()URL of the current page
getTitle()Title of the current page
isLoading()Whether it is loading
isCrashed()Whether the page's process is gone

Exchanging data with the page:

MethodDescription
executeJavaScript()Runs code in the page and gets the result back
send()Sends a message to the page's preload script

Destroying:

MethodDescription
close()Destroys the page and frees its memory
isDestroyed()Whether it has been destroyed

It also has addEventListener() and removeEventListener(), inherited from EventTarget.

Events ​

Listen with addEventListener. A misspelled event name doesn't throw: it is treated as a custom event that the page never fires, so check names against the table below.

EventWhen it fires
will-navigateThe page itself is about to navigate to another URL and hasn't started yet. Cancelable
did-start-loadingLoading starts
did-navigateThe page has switched to a new document
did-stop-loadingLoading stops. Fires on both success and failure
did-finish-loadLoading finishes
did-fail-loadLoading fails
page-title-updatedThe title changes
ipc-messageThe page's preload script calls ipcRenderer.send
preload-errorThe preload script throws while running
console-messageThe page calls a console method, or an exception goes uncaught
render-process-goneThe page's process is gone
destroyedDestroyed by close()

will-navigate is the only cancelable event. The others fire after the fact: cancelable is false, and calling preventDefault() has no effect.

For a successful load, the four loading events arrive in the order did-start-loading → did-navigate → did-stop-loading → did-finish-load. When the user taps a link in the page that goes to another page, the same four events arrive.

After destruction ​

After you call close(), every method other than close() and isDestroyed() throws TypeError: Object has been destroyed; loadURL() returns a Promise rejected with the same error. Destruction can't be undone; to show a web page again, create a new WebView.

How values are passed ​

The result of executeJavaScript(), message arguments, and the return value of invoke are all passed as JSON.

ValueAfter passing
Numbers, strings, booleans, null, arrays, plain objectsUnchanged
Order of object membersSame as in the page. The exception is an object produced by executeJavaScript running multiple statements: the values are correct, but the order isn't guaranteed
undefinedStays undefined as a standalone value; the member disappears inside an object; becomes null inside an array
DatesStrings, such as '1970-01-01T00:00:00.000Z'
NaN, Infinitynull
FunctionsA message containing a function throws TypeError immediately; an executeJavaScript result that is a function is rejected; when the result is an object with a function member, that member disappears
MapEmpty object {}
DOM nodesAn executeJavaScript result that is a DOM node is rejected

Limits of local web pages ​

A page loaded with loadFile() has a URL starting with file://. It differs from a page loaded from a server in a few ways.

Local web page
Referencing stylesheets, classic scripts, and images by relative pathWorks
? and # in the URLWork; the page can read them
localStorage, cookiesWork
<script type="module">Doesn't run
Reading local files with fetch or XMLHttpRequestFails
OriginAll local web pages share one: file://. Their localStorage is shared
Which files it can readPages inside the app bundle: the whole app bundle. Pages elsewhere: their own directory and its subdirectories. The simulator doesn't enforce this limit; test it on a device

Requests from a local web page to https:// APIs are unaffected; only reading local files is restricted.

loadFile() suits static pages and pages bundled the traditional way (a single classic <script>). Single-page apps that use module scripts (such as Vite's default build output) can't be loaded locally yet.

Examples ​

js
const web = new WebView();
const contents = web.webContents;
contents.addEventListener('did-fail-load', (e) => {
  console.log('Load failed', e.errorCode, e.validatedURL);
});
await contents.loadURL('https://example.com/');
console.log(contents.getURL(), contents.isLoading());

Result: On success, it prints https://example.com/ false. On failure, it first prints Load failed with the error code, and the await line throws the rejection error.

Comparison with Electron ​

ElectronHereDifference
contents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => …)contents.addEventListener('did-fail-load', (e) => …)Data is on e, with the same field names
contents.on('will-navigate', (details) => details.preventDefault())contents.addEventListener('will-navigate', (e) => e.preventDefault())Adds navigationType; no frame or initiator
httpStatusText on did-navigateNoneThe system doesn't provide it
details.reason on render-process-goneNoneThe system doesn't give a reason
errorCode on did-fail-load (-105 and so on)errorCode (-1003 and so on)Different numbers
contents.executeJavaScript(code)SameCode with multiple statements doesn't wait for Promises, and returned objects don't guarantee member order; results are passed as JSON (dates are strings, Map is {})
contents.on('ipc-message', (event, channel, ...args) => …)contents.addEventListener('ipc-message', (e) => …)e.channel, e.args
contents.send(channel, ...args), contents.ipc.handle(channel, listener)Same
contents.sessionSameSee session
contents.loadFile(filePath, { query, search, hash })SameRelative paths start from the app bundle. Local web pages have more limits than in Electron; see Limits of local web pages
contents.navigationHistory.goBack()Same
contents.loadURL(url, { baseURLForDataURL })SameThe second argument supports only baseURLForDataURL
contents.on('console-message', (details) => …)contents.addEventListener('console-message', (e) => …)No frame; uncaught exceptions also fire it
contents.close() / isDestroyed() / 'destroyed'Same

Corresponding iOS API ​

ObjC (WKWebView)JS
[webView loadRequest:]contents.loadURL(url)
[webView loadHTMLString:html baseURL:base]contents.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(html), { baseURLForDataURL: base })
[webView loadFileURL:allowingReadAccessToURL:]contents.loadFile(filePath). The runtime decides the readable directory from the file's location
webView.URLcontents.getURL()
webView.titlecontents.getTitle(), the page-title-updated event
webView.loadingcontents.isLoading(), the did-start-loading / did-stop-loading events
[webView stopLoading]contents.stop()
[webView reload]contents.reload()
webView.canGoBack / canGoForwardcontents.navigationHistory.canGoBack() / canGoForward()
[webView goBack] / [webView goForward]contents.navigationHistory.goBack() / goForward()
[webView evaluateJavaScript:completionHandler:], callAsyncJavaScript:…contents.executeJavaScript(code)
WKScriptMessageHandlerWithReplyipcRenderer in the preload script; the ipc-message event and ipc.handle on the app side
webView:decidePolicyForNavigationAction:decisionHandler:The will-navigate event; decisionHandler(.cancel) corresponds to e.preventDefault()
navigationAction.navigationTypeThe event's navigationType
webView:didCommitNavigation:The did-navigate event
webView:didFinishNavigation:The did-finish-load event
webView:didFailNavigation:withError:, webView:didFailProvisionalNavigation:withError:The did-fail-load event
webViewWebContentProcessDidTerminate:The render-process-gone event
Releasing the WKWebViewcontents.close()

See also ​