<webview> Tag
Description: |
Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. Your app can control the appearance of the webview and interact with the web content, initiate navigations in an embedded web page, react to error events that happen within it, and more (see Usage).
|
Availability: |
Stable since Chrome 25.
|
Permissions: |
"webview"
|
Usage
Use the webview
tag to embed 'guest' content
(such as web pages) in your Chrome App.
The guest content is contained within the webview
container;
an embedder page within your Chrome App controls
how the guest content is laid out and rendered.
Different from the iframe
,
the webview
runs in a separate process than your app;
it doesn't have the same permissions as your app and
all interactions between your app and embedded content will be asynchronous.
This keeps your app safe from the embedded content.
Example
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="http://www.google.com/" style="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 in app.js
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:
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("loadstart", loadstart); webview.addEventListener("loadstop", loadstop); }
Tag attributes
src
<webview id="foo" src="http://www.google.com/" style="width:640px; height:480px"></webview>
Returns the visible URL. Mirrors the logic in the browser's omnibox: either returning a pending new navigation if initiated by the embedder page, or the last committed navigation. 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!"
.
partition
<webview id="foo" src="http://www.google.com/" style="width:640px; height:480px" partition="persist:googlepluswidgets"></webview>
Storage partition ID used by the webview
tag.
If the storage partition ID starts with persist:
(partition="persist:googlepluswidgets"
),
the webview
will use a persistent storage partition
available to all guests in the app
with the same storage partition ID.
If the ID is unset or if there is no 'persist':
prefix,
the webview
will use an in-memory storage partition.
This value can only be modified before the first navigation,
since the storage partition of an active renderer process cannot change.
Subsequent attempts to modify the value will fail with a DOM exception.
By assigning the same partition ID,
multiple webviews can share the same storage partition.
Exception thrown:
The partition attribute must be valid for navigation to proceed.
In the case of an invalid partition, such as partition="persist:"
,
the src attribute cannot be set and an exception is thrown.
autosize
<webview id="foo" src="http://www.google.com/" style="width:640px; height:480px" autosize="on" minwidth="576" minheight="432"></webview>
If "on", the webview
will container will automatically resize within the bounds specified
by the attributes minwidth
, minheight
,
maxwidth
, and maxheight
.
These contraints do not impact the webview
UNLESS autosize
is enabled.
When autosize is enabled, the webview
container size cannot be less than the minimum values
or greater than the maximum.
name
<webview src="https://www.google.com/" name="google-view"></webview>
This sets the guest content's window.name
object.
Summary
Types | |
---|---|
ClearDataOptions | |
ClearDataTypeSet | |
InjectDetails | |
ContentWindow | |
DialogController | |
FindCallbackResults | |
FindOptions | |
NewWindow | |
MediaPermissionRequest | |
GeolocationPermissionRequest | |
PointerLockPermissionRequest | |
DownloadPermissionRequest | |
LoadPluginPermissionRequest | |
SelectionRect | |
WebRequestEventInteface | |
Properties | |
contentWindow | |
request | |
Methods | |
back −
<webview>.back()
| |
canGoBack −
boolean
<webview>.canGoBack()
| |
canGoForward −
boolean
<webview>.canGoForward()
| |
clearData −
<webview>.clearData( ClearDataOptions options, ClearDataTypeSet types, function callback)
| |
executeScript −
<webview>.executeScript( InjectDetails details, function callback)
| |
find −
<webview>.find(string searchText, FindOptions options, function callback)
| |
forward −
<webview>.forward()
| |
getProcessId −
integer
<webview>.getProcessId()
| |
getUserAgent −
string
<webview>.getUserAgent()
| |
go −
<webview>.go(integer relativeIndex)
| |
insertCSS −
<webview>.insertCSS( InjectDetails details, function callback)
| |
isUserAgentOverridden −
<webview>.isUserAgentOverridden()
| |
reload −
<webview>.reload()
| |
setUserAgentOverride −
<webview>.setUserAgentOverride(string userAgent)
| |
stop −
<webview>.stop()
| |
stopFinding −
<webview>.stopFinding(enum of
| |
terminate −
<webview>.terminate()
| |
DOM Events | |
close | |
consolemessage | |
contentload | |
dialog | |
exit | |
findupdate | |
loadabort | |
loadcommit | |
loadredirect | |
loadstart | |
loadstop | |
newwindow | |
permissionrequest | |
responsive | |
sizechanged | |
unresponsive |
Types
ClearDataOptions
properties | ||
---|---|---|
double | (optional) since |
Clear data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data).
|
ClearDataTypeSet
properties | ||
---|---|---|
boolean | (optional) appcache | Websites' appcaches. |
boolean | (optional) cache |
The partition's cache. Note: This clears the entire cache regardless of the age passed to clearData .
|
boolean | (optional) cookies | The partition's cookies. |
boolean | (optional) downloads | The partition's download list. |
boolean | (optional) fileSystems | Websites' filesystems. |
boolean | (optional) formData | The partition's stored form data. |
boolean | (optional) history | The partition's history. |
boolean | (optional) indexedDB | Websites' IndexedDB data. |
boolean | (optional) localStorage | Websites' local storage data. |
boolean | (optional) serverBoundCertificates | Server-bound certificates. |
boolean | (optional) pluginData | Plugins' data. |
boolean | (optional) passwords | Stored passwords. |
boolean | (optional) webSQL | Websites' WebSQL data. |
InjectDetails
properties | ||
---|---|---|
string | (optional) code | JavaScript or CSS code to inject. |
string | (optional) file | JavaScript or CSS file to inject. |
ContentWindow
methods | |||||||||
---|---|---|---|---|---|---|---|---|---|
postMessage
ContentWindow.postMessage(any message, string targetOrigin)
Posts a message to the embedded web content as long as the embedded content is displaying a page from the target origin. This method is available once the page has completed loading. Listen for the contentload event and then call the method. The guest will be able to send replies to the embedder by posting message to This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a
|
DialogController
methods | ||||||
---|---|---|---|---|---|---|
ok
DialogController.ok(string response)
Accept the dialog. Equivalent to clicking OK in an
| ||||||
cancel
DialogController.cancel()
Reject the dialog. Equivalent to clicking Cancel in a |
FindCallbackResults
properties | ||
---|---|---|
integer | numberOfMatches |
The number of times searchText was matched on the page.
|
integer | activeMatchOrdinal | The ordinal number of the current match. |
SelectionRect | selectionRect | Describes a rectangle around the active match in screen coordinates. |
boolean | canceled | Indicates whether this find request was canceled. |
FindOptions
properties | ||
---|---|---|
boolean | (optional) backward |
Flag to find matches in reverse order. The default value is false .
|
boolean | (optional) matchCase |
Flag to match with case-sensitivity. The default value is false .
|
NewWindow
methods | ||||||
---|---|---|---|---|---|---|
attach
NewWindow.attach(object webview)
Attach the requested target page to an existing
| ||||||
discard
NewWindow.discard()
Cancel the new window request. |
MediaPermissionRequest
properties | ||
---|---|---|
string | url | The URL of the frame requesting access to user media. |
methods | ||
allow
MediaPermissionRequest.allow()
Allow the permission request. | ||
deny
MediaPermissionRequest.deny()
Deny the permission request. This is the default behavior if |
GeolocationPermissionRequest
properties | ||
---|---|---|
string | url | The URL of the frame requesting access to geolocation data. |
methods | ||
allow
GeolocationPermissionRequest.allow()
Allow the permission request. | ||
deny
GeolocationPermissionRequest.deny()
Deny the permission request. This is the default behavior if |
PointerLockPermissionRequest
properties | ||
---|---|---|
boolean | userGesture | Whether or not pointer lock was requested as a result of a user input gesture. |
boolean | lastUnlockedBySelf | Whether or not the requesting frame was the most recent client to hold pointer lock. |
string | url | The URL of the frame requesting pointer lock. |
methods | ||
allow
PointerLockPermissionRequest.allow()
Allow the permission request. | ||
deny
PointerLockPermissionRequest.deny()
Deny the permission request. This is the default behavior if |
DownloadPermissionRequest
properties | ||
---|---|---|
string | requestMethod |
The HTTP request type (e.g. GET ) associated with the download request.
|
string | url | The requested download URL. |
methods | ||
allow
DownloadPermissionRequest.allow()
Allow the permission request. | ||
deny
DownloadPermissionRequest.deny()
Deny the permission request. This is the default behavior if |
LoadPluginPermissionRequest
properties | ||
---|---|---|
string | identifier | The plugin's identifier string. |
string | name | The plugin's display name. |
methods | ||
allow
LoadPluginPermissionRequest.allow()
Allow the permission request. This is the default behavior if | ||
deny
LoadPluginPermissionRequest.deny()
Deny the permission request. |
SelectionRect
properties | ||
---|---|---|
integer | left | Distance from the left edge of the screen to the left edge of the rectangle. |
integer | top | Distance from the top edge of the screen to the top edge of the rectangle. |
integer | width | Width of the rectangle. |
integer | height | Height of the rectangle. |
WebRequestEventInteface
Properties
ContentWindow | <webview>.contentWindow |
Object reference which can be used to post messages into the guest page. |
WebRequestEventInteface | <webview>.request |
Interface which provides access to webRequest events on the guest page. |
Methods
back
<webview>.back()
Navigates backward one history entry if possible. Equivalent to go(-1)
.
canGoBack
boolean
<webview>.canGoBack()
Indicates whether or not it is possible to navigate backward through history.
canGoForward
boolean
<webview>.canGoForward()
Indicates whether or not it is possible to navigate forward through history.
clearData
<webview>.clearData( ClearDataOptions options, ClearDataTypeSet types, function callback)
Clears browsing data for the webview
partition.
Parameters | ||
---|---|---|
ClearDataOptions | options | Options determining exactly what data to clear. |
ClearDataTypeSet | types | The types of data to be cleared. |
function | (optional) callback |
Called after the data has been successfully cleared.
If you specify the callback parameter, it should be a function that looks like this: function() {...};
|
executeScript
<webview>.executeScript( InjectDetails details, function callback)
Injects JavaScript code into the guest page.
The following sample code uses script injection to set the guest page's background color to red:
webview.executeScript({ code: "document.body.bgColor = 'red'" });
Parameters | |||||
---|---|---|---|---|---|
InjectDetails | details | Details of the script to run. | |||
function | (optional) callback |
Called after all the JavaScript has been executed.
If you specify the callback parameter, it should be a function that looks like this: function(array of any result) {...};
|
find
<webview>.find(string searchText, FindOptions options, function callback)
Initiates a find-in-page request.
Parameters | |||||
---|---|---|---|---|---|
string | searchText | The string to find in the page. | |||
FindOptions | (optional) options | Options for the find request. | |||
function | (optional) callback |
Called after all find results have been returned for this find request.
If you specify the callback parameter, it should be a function that looks like this: function( FindCallbackResults results) {...};
|
forward
<webview>.forward()
Navigates forward one history entry if possible. Equivalent to go(1)
.
getProcessId
integer
<webview>.getProcessId()
Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID.
getUserAgent
string
<webview>.getUserAgent()
Returns the user agent string used by the webview for guest page requests.
go
<webview>.go(integer relativeIndex)
Navigates to a history entry using a history index relative to the current navigation. If the requested navigation is impossible, this method has no effect.
Parameters | ||
---|---|---|
integer | relativeIndex |
Relative history index to which the webview should be navigated. For example, a value of 2 will navigate forward 2 history entries if possible; a value of -3 will navigate backward 3 entries.
|
insertCSS
<webview>.insertCSS( InjectDetails details, function callback)
Injects CSS into the guest page.
Parameters | ||
---|---|---|
InjectDetails | details | Details of the CSS to insert. |
function | (optional) callback |
Called after the CSS has been inserted.
If you specify the callback parameter, it should be a function that looks like this: function() {...};
|
isUserAgentOverridden
<webview>.isUserAgentOverridden()
Indicates whether or not the webview's user agent string has been overridden by webviewTag.setUserAgentOverride
reload
<webview>.reload()
Reloads the current top-level page.
setUserAgentOverride
<webview>.setUserAgentOverride(string userAgent)
Override the user agent string used by the webview for guest page requests.
Parameters | ||
---|---|---|
string | userAgent | The user agent string to use. |
stop
<webview>.stop()
Stops loading the current <webview> navigation if in progress.
stopFinding
<webview>.stopFinding(enum of "clear"
, "keep"
, or "activate"
action)
Ends the current find session (clearing all highlighting) and cancels all find requests in progress.
Parameters | ||
---|---|---|
enum of "clear" , "keep" , or "activate" |
(optional) action |
Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep .
|
terminate
<webview>.terminate()
Forcibly kills the guest web page's renderer process. This may affect multiple webview
tags in the current app if they share the same process, but it will not affect webview
tags in other apps.
DOM Events
Event
object which can have
additional properties as listed with each event.close
Fired when the guest window attempts to close itself.
The following example code navigates the webview to about:blank
when the guest attempts to close itself.
webview.addEventListener('close', function() { webview.src = 'about:blank'; });
consolemessage
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.
webview.addEventListener('consolemessage', function(e) { console.log('Guest page logged a message: ', e.message); });
contentload
Fired when the guest window fires a load
event.
The following example code modifies the default font size of the guest's body
element after the page loads:
webview.addEventListener('contentload', function() { webview.executeScript({ code: 'document.body.style.fontSize = "42px"' }); });
dialog
Fired when the guest window attempts to open a modal dialog via window.alert
, window.confirm
, or window.prompt
.
Handling this event will block the guest process until each event listener returns or the dialog
object becomes unreachable (if preventDefault()
was called.)
The default behavior is to cancel the dialog.
"alert"
, "confirm"
, or "prompt"
exit
Fired when the process rendering the guest web content has exited.
The following example code will show a farewell message whenever the guest page crashes:
webview.addEventListener('exit', function(e) { if (e.reason === 'crash') { webview.src = 'data:text/plain,Goodbye, world!'; } });
"normal"
, "abnormal"
, "crash"
, or "kill"
findupdate
Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found.
searchText
on the page so far.
0
until then.
findupdate
events will be fired until more find requests are made.
loadabort
Fired when a top-level load has aborted without committing.
"networkError"
, "download"
, "canceled"
, "sslError"
, or "safeBrowsingError"
loadcommit
Fired when a load has committed.
loadredirect
Fired when a top-level load request has redirected to a different URL.
loadstart
Fired when a load has begun.
loadstop
Fired when all loads in the guest page (including all subframes) have completed. Fires in addition to any related loadcommit
or loadabort
events, which occur per-frame.
newwindow
Fired when the guest page attempts to open a new browser window.
The following example code will create and navigate a new webview
in the embedder for each requested new window:
webview.addEventListener('newwindow', function(e) { var newWebview = document.createElement('webview'); document.body.appendChild(newWebview); e.window.attach(newWebview); });
webview
element or explicitly discard the request.
"ignore"
, "save_to_disk"
, "current_tab"
, "new_background_tab"
, "new_foreground_tab"
, "new_window"
, or "new_popup"
permissionrequest
Fired when the guest page needs to request special permission from the embedder.
The following example code will grant the guest page access to the webkitGetUserMedia
API. Note that an app using this example code must itself specify audioCapture
and/or videoCapture
manifest permissions:
webview.addEventListener('permissionrequest', function(e) { if (e.permission === 'media') { e.request.allow(); } });
"media"
, "geolocation"
, "pointerLock"
, "download"
, or "loadplugin"
responsive
Fired when the process rendering the guest web content has become responsive again after being unresponsive.
The following example code will fade the webview
element in or out as it becomes responsive or unresponsive:
webview.style.webkitTransition = 'opacity 250ms'; webview.addEventListener('unresponsive', function() { webview.style.opacity = '0.5'; }); webview.addEventListener('responsive', function() { webview.style.opacity = '1'; });
sizechanged
Fired when the embedded web content has been resized. Only fires if autosize
is enabled.
unresponsive
Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again.