- CHROME
- CHROME OS
- CHROME APIS
<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: | Since Chrome 38. |
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);
}
Debugging the contents of a <webview>
If you want to inspect the contents of a <webview>
tag in DevTools, navigate to chrome://inspect/#apps
, and then click on inspect
for the page inside of the webview
(it will be indented to the right under the app that the webview
is embedded in).
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 cannot be cleared or removed once it has been set, unless the webview
is removed from the DOM.
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.
allowtransparency
<webview id="foo" src="http://www.google.com/" style="width:640px; height:480px" allowtransparency></webview>
If present, portions of the embedder could be visible through the webview
, where the contents are transparent. Without allowtransparency
enabled, no part of the embedder will be shown through the webview
, even if elements exist that are specified as transparent.
This does not affect transparency within the contents of the webview
itself.
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
container will automatically resize within the bounds specified by the attributes minwidth
, minheight
, maxwidth
, and maxheight
. These constraints 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.
Accessing packaged resources
By default, webviews are prevented from loading any resources packaged with the app. However, webview partitions may be granted access to these resources via a webview.partitions
section in the app manifest. Partitions may be granted access to a set of files by matching partition name patterns with file name patterns. Both sorts of patterns may contain the *
wildcard.
Consider the following manifest.json
snippet:
{
"name": "My extension",
...
"permissions": [
"webview"
],
"webview": {
"partitions": [
// In this example, any <webview partition="static"> or
// <webview partition="persist:static"> will have access to
// header.html, footer.html, and static.png.
{
"name": "static",
"accessible_resources": ["header.html", "footer.html", "static.png"]
},
// Also, any webview with a partition name beginning with "trusted"
// (e.g., "trusted-foo", "persist:trusted-bar") will have access to
// ".html" files beginning with "local_", as well as ".png" and ".js"
// files.
{
"name": "trusted*",
"accessible_resources": ["local_*.html", "*.png", "*.js"]
}
// In addition, any <webview partition="trusted-audio"> or
// <webview partition="persist:trusted-audio"> will have access to
// ".mp3" files. Note that this is in addition to "local_*.html",
// "*.png", "*.js" because "trusted-audio" also matches the "trusted*"
// pattern.
{
"name": "trusted-audio",
"accessible_resources": ["*.mp3"]
}
// Webviews in any other partition are denied access to packaged
// resources.
]
}
}
Summary
Types | |
---|---|
ClearDataOptions | |
ClearDataTypeSet | |
ContextType | |
InjectDetails | |
InjectionItems | |
ContentScriptDetails | |
ContextMenuCreateProperties | |
ContextMenuUpdateProperties | |
ContextMenus | |
ContentWindow | |
DialogController | |
FindCallbackResults | |
FindOptions | |
NewWindow | |
MediaPermissionRequest | |
GeolocationPermissionRequest | |
PointerLockPermissionRequest | |
DownloadPermissionRequest | |
FileSystemPermissionRequest | |
FullscreenPermissionRequest | |
LoadPluginPermissionRequest | |
SelectionRect | |
WebRequestEventInterface | |
ZoomMode | |
Properties | |
contentWindow | |
request | |
contextMenus | |
Methods | |
getAudioState − <webview>.getAudioState(function callback) |
|
setAudioMuted − <webview>.setAudioMuted(boolean mute) |
|
isAudioMuted − <webview>.isAudioMuted(function callback) |
|
captureVisibleRegion − <webview>.captureVisibleRegion(object options, function callback) |
|
addContentScripts − <webview>.addContentScripts(array of ContentScriptDetails contentScriptList) |
|
back − <webview>.back(function callback) |
|
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(function callback) |
|
getProcessId − integer <webview>.getProcessId() |
|
getUserAgent − string <webview>.getUserAgent() |
|
getZoom − <webview>.getZoom(function callback) |
|
getZoomMode − <webview>.getZoomMode(function callback) |
|
go − <webview>.go(integer relativeIndex, function callback) |
|
insertCSS − <webview>.insertCSS( InjectDetails details, function callback) |
|
isUserAgentOverridden − <webview>.isUserAgentOverridden() |
|
print − <webview>.print() |
|
reload − <webview>.reload() |
|
removeContentScripts − <webview>.removeContentScripts(array of string scriptNameList) |
|
setUserAgentOverride − <webview>.setUserAgentOverride(string userAgent) |
|
setZoom − <webview>.setZoom(double zoomFactor, function callback) |
|
setZoomMode − <webview>.setZoomMode( ZoomMode ZoomMode, function callback) |
|
stop − <webview>.stop() |
|
stopFinding − <webview>.stopFinding(enum of |
|
loadDataWithBaseUrl − <webview>.loadDataWithBaseUrl(string dataUrl, string baseUrl, string virtualUrl) |
|
setSpatialNavigationEnabled − <webview>.setSpatialNavigationEnabled(boolean enabled) |
|
isSpatialNavigationEnabled − <webview>.isSpatialNavigationEnabled(function callback) |
|
terminate − <webview>.terminate() |
|
DOM Events | |
close | |
consolemessage | |
contentload | |
dialog | |
exit | |
findupdate | |
loadabort | |
loadcommit | |
loadredirect | |
loadstart | |
loadstop | |
newwindow | |
permissionrequest | |
responsive | |
sizechanged | |
unresponsive | |
zoomchange |
Types
ClearDataOptions
Options that determine what data should be cleared byclearData
.
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 |
ClearDataTypeSet
A set of data types. Missing properties are interpreted asfalse
.
properties | ||
---|---|---|
boolean | (optional) appcache |
Websites' appcaches. |
boolean | (optional) cache |
Since Chrome 44. Since Chrome 43. |
boolean | (optional) cookies |
The partition's cookies. |
boolean | (optional) sessionCookies |
Since Chrome 58. The partition's session cookies. |
boolean | (optional) persistentCookies |
Since Chrome 58. The partition's persistent cookies. |
boolean | (optional) fileSystems |
Websites' filesystems. |
boolean | (optional) indexedDB |
Websites' IndexedDB data. |
boolean | (optional) localStorage |
Websites' local storage data. |
boolean | (optional) webSQL |
Websites' WebSQL data. |
ContextType
The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts.Enum |
---|
"all" , "page" , "frame" , "selection" , "link" , "editable" , "image" , "video" , or "audio" |
InjectDetails
Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time.properties | ||
---|---|---|
string | (optional) code |
JavaScript or CSS code to inject. |
string | (optional) file |
JavaScript or CSS file to inject. |
InjectionItems
Since Chrome 44.
The type of injection item: code or a set of files.properties | ||
---|---|---|
string | (optional) code |
JavaScript code or CSS to be injected into matching pages. |
array of string | (optional) files |
The list of JavaScript or CSS files to be injected into matching pages. These are injected in the order they appear in this array. |
ContentScriptDetails
Since Chrome 44.
Details of the content script to inject. Refer to the content scripts documentation for more details.properties | ||
---|---|---|
string | name |
The name of the content script to inject. |
array of string | matches |
Specifies which pages this content script will be injected into. |
array of string | (optional) exclude_matches |
Excludes pages that this content script would otherwise be injected into. |
boolean | (optional) match_about_blank |
Whether to insert the content script on about:blank and about:srcdoc. Content scripts will only be injected on pages when their inherit URL is matched by one of the declared patterns in the matches field. The inherit URL is the URL of the document that created the frame or window. Content scripts cannot be inserted in sandboxed frames. |
InjectionItems | (optional) css |
The CSS code or a list of CSS files to be injected into matching pages. These are injected in the order they appear, before any DOM is constructed or displayed for the page. |
InjectionItems | (optional) js |
The JavaScript code or a list of JavaScript files to be injected into matching pages. These are injected in the order they appear. |
enum of "document_start" , "document_end" , or "document_idle" |
(optional) run_at |
The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". |
boolean | (optional) all_frames |
If |
array of string | (optional) include_globs |
Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword. |
array of string | (optional) exclude_globs |
Applied after matches to exclude URLs that match this glob. Intended to emulate the @exclude Greasemonkey keyword. |
ContextMenuCreateProperties
Since Chrome 44.
properties | ||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
contextMenus.ItemType | (optional) type |
The type of menu item. Defaults to 'normal' if not specified. |
||||||||||||||||||||||||||||||||||||||||||
string | (optional) id |
The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. |
||||||||||||||||||||||||||||||||||||||||||
string | (optional) title |
The text to be displayed in the item; this is required unless |
||||||||||||||||||||||||||||||||||||||||||
boolean | (optional) checked |
The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. |
||||||||||||||||||||||||||||||||||||||||||
array of ContextType | (optional) contexts |
List of contexts this menu item will appear in. Defaults to ['page'] if not specified. |
||||||||||||||||||||||||||||||||||||||||||
function | (optional) onclick |
A function that will be called back when the menu item is clicked.
|
||||||||||||||||||||||||||||||||||||||||||
integer or string | (optional) parentId |
The ID of a parent menu item; this makes the item a child of a previously added item. |
||||||||||||||||||||||||||||||||||||||||||
array of string | (optional) documentUrlPatterns |
Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. |
||||||||||||||||||||||||||||||||||||||||||
array of string | (optional) targetUrlPatterns |
Similar to documentUrlPatterns, but lets you filter based on the |
||||||||||||||||||||||||||||||||||||||||||
boolean | (optional) enabled |
Whether this context menu item is enabled or disabled. Defaults to |
ContextMenuUpdateProperties
properties | ||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
contextMenus.ItemType | (optional) type |
The type of menu item. |
||||||||||||||||||||||||||||||||||||||||||
string | (optional) title |
The text to be displayed in the item |
||||||||||||||||||||||||||||||||||||||||||
boolean | (optional) checked |
The state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. |
||||||||||||||||||||||||||||||||||||||||||
array of ContextType | (optional) contexts |
List of contexts this menu item will appear in. |
||||||||||||||||||||||||||||||||||||||||||
function | (optional) onclick |
A function that will be called back when the menu item is clicked.
|
||||||||||||||||||||||||||||||||||||||||||
integer or string | (optional) parentId |
The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants. |
||||||||||||||||||||||||||||||||||||||||||
array of string | (optional) documentUrlPatterns |
Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. |
||||||||||||||||||||||||||||||||||||||||||
array of string | (optional) targetUrlPatterns |
Similar to documentUrlPatterns, but lets you filter based on the |
||||||||||||||||||||||||||||||||||||||||||
boolean | (optional) enabled |
Whether this context menu item is enabled or disabled. |
ContextMenus
Since Chrome 44.
onShow
Fired before showing a context menu on this webview
. Can be used to disable this context menu by calling event.preventDefault()
.
methods | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
createinteger or string ContextMenus.create( ContextMenuCreateProperties createProperties, function callback) Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in runtime.lastError).
|
||||||||||||
updateContextMenus.update(integer or string id, ContextMenuUpdateProperties updateProperties, function callback) Updates a previously created context menu item.
|
||||||||||||
removeContextMenus.remove(integer or string menuItemId, function callback) Removes a context menu item.
|
||||||||||||
removeAllContextMenus.removeAll(function callback) Removes all context menu items added to this
|
||||||||||||
events | ||||||||||||
addListeneronShow.addListener(function callback)
|
ContentWindow
Messaging handle to a guest window.methods | |||||||||
---|---|---|---|---|---|---|---|---|---|
postMessageContentWindow.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
Interface attached todialog
DOM events.
methods | ||||||
---|---|---|---|---|---|---|
okDialogController.ok(string response) Accept the dialog. Equivalent to clicking OK in an
|
||||||
cancelDialogController.cancel() Reject the dialog. Equivalent to clicking Cancel in a |
FindCallbackResults
Contains all of the results of the find request.properties | ||
---|---|---|
integer | numberOfMatches |
The number of times |
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
Options for the find request.properties | ||
---|---|---|
boolean | (optional) backward |
Flag to find matches in reverse order. The default value is |
boolean | (optional) matchCase |
Flag to match with case-sensitivity. The default value is |
NewWindow
Interface attached tonewwindow
DOM events.
methods | ||||||
---|---|---|---|---|---|---|
attachNewWindow.attach(object webview) Attach the requested target page to an existing
|
||||||
discardNewWindow.discard() Cancel the new window request. |
MediaPermissionRequest
The type ofrequest
object which accompanies a media
permissionrequest DOM event.
properties | ||
---|---|---|
string | url |
The URL of the frame requesting access to user media. |
methods | ||
allowMediaPermissionRequest.allow() Allow the permission request. |
||
denyMediaPermissionRequest.deny() Deny the permission request. This is the default behavior if |
GeolocationPermissionRequest
The type ofrequest
object which accompanies a geolocation
permissionrequest DOM event.
properties | ||
---|---|---|
string | url |
The URL of the frame requesting access to geolocation data. |
methods | ||
allowGeolocationPermissionRequest.allow() Allow the permission request. |
||
denyGeolocationPermissionRequest.deny() Deny the permission request. This is the default behavior if |
PointerLockPermissionRequest
The type ofrequest
object which accompanies a pointerLock
permissionrequest DOM event.
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 | ||
allowPointerLockPermissionRequest.allow() Allow the permission request. |
||
denyPointerLockPermissionRequest.deny() Deny the permission request. This is the default behavior if |
DownloadPermissionRequest
The type ofrequest
object which accompanies a download
permissionrequest DOM event.
properties | ||
---|---|---|
string | requestMethod |
The HTTP request type (e.g. |
string | url |
The requested download URL. |
methods | ||
allowDownloadPermissionRequest.allow() Allow the permission request. |
||
denyDownloadPermissionRequest.deny() Deny the permission request. This is the default behavior if |
FileSystemPermissionRequest
The type ofrequest
object which accompanies a filesystem
permissionrequest DOM event.
properties | ||
---|---|---|
string | url |
The URL of the frame requesting access to local file system. |
methods | ||
allowFileSystemPermissionRequest.allow() Allow the permission request. |
||
denyFileSystemPermissionRequest.deny() Deny the permission request. |
FullscreenPermissionRequest
Since Chrome 43.
The type ofrequest
object which accompanies a fullscreen
permissionrequest DOM event.
properties | ||
---|---|---|
string | origin |
The origin of the frame inside the |
methods | ||
allowFullscreenPermissionRequest.allow() Allow the permission request. |
||
denyFullscreenPermissionRequest.deny() Deny the permission request. |
LoadPluginPermissionRequest
The type ofrequest
object which accompanies a loadplugin
permissionrequest DOM event.
properties | ||
---|---|---|
string | identifier |
The plugin's identifier string. |
string | name |
The plugin's display name. |
methods | ||
allowLoadPluginPermissionRequest.allow() Allow the permission request. This is the default behavior if |
||
denyLoadPluginPermissionRequest.deny() Deny the permission request. |
SelectionRect
Describes a rectangle in screen coordinates.
The containment semantics are array-like; that is, the coordinate (left, top)
is considered to be contained by the rectangle, but the coordinate (left + width, top)
is not.
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. |
WebRequestEventInterface
Since Chrome 44.
Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts. Note: The chrome.webRequest.onActionIgnored event is not supported for webviews.To illustrate how usage differs from the extensions webRequest API, consider the following example code which blocks any guest requests for URLs which match *://www.evil.com/*
:
webview.request.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["*://www.evil.com/*"]},
["blocking"]);
Additionally, this interface supports declarative webRequest rules through onRequest
and onMessage
events. See declarativeWebRequest for API details.
chrome.webViewRequest.*
counterparts. The following example code declaratively blocks all requests to "example.com"
on the webview myWebview
:
var rule = {
conditions: [
new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } })
],
actions: [ new chrome.webViewRequest.CancelRequest() ]
};
myWebview.request.onRequest.addRules([rule]);
ZoomMode
Defines the how zooming is handled in thewebview
.
Enum |
---|
|
Properties
ContentWindow | <webview>.contentWindow |
Object reference which can be used to post messages into the guest page. |
WebRequestEventInterface | <webview>.request |
Interface which provides access to webRequest events on the guest page. |
ContextMenus | <webview>.contextMenus |
Since Chrome 44. Similar to chrome's ContextMenus API, but applies towebview instead of browser. Use the webview.contextMenus API to add items to webview 's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. |
Methods
getAudioState
<webview>.getAudioState(function callback)
Since Chrome 62.
Queries audio state.
Parameters | |||||
---|---|---|---|---|---|
function | callback |
The callback parameter should be a function that looks like this: function(boolean audible) {...};
|
setAudioMuted
<webview>.setAudioMuted(boolean mute)
Since Chrome 62.
Sets audio mute state of the webview.
Parameters | ||
---|---|---|
boolean | mute |
Mute audio value |
isAudioMuted
<webview>.isAudioMuted(function callback)
Since Chrome 62.
Queries whether audio is muted.
Parameters | |||||
---|---|---|---|---|---|
function | callback |
The callback parameter should be a function that looks like this: function(boolean muted) {...};
|
captureVisibleRegion
<webview>.captureVisibleRegion(object options, function callback)
Since Chrome 50.
Captures the visible region of the webview.
Parameters | ||||||||
---|---|---|---|---|---|---|---|---|
object | (optional) options |
Details about the format and quality of an image.
|
||||||
function | callback |
The callback parameter should be a function that looks like this: function(string dataUrl) {...};
|
addContentScripts
<webview>.addContentScripts(array of ContentScriptDetails contentScriptList)
Since Chrome 44.
Adds content script injection rules to the webview
. When the webview
navigates to a page matching one or more rules, the associated scripts will be injected. You can programmatically add rules or update existing rules.
The following example adds two rules to the webview
: 'myRule' and 'anotherRule'.
webview.addContentScripts([
{
name: 'myRule',
matches: ['http://www.foo.com/*'],
css: { files: ['mystyles.css'] },
js: { files: ['jquery.js', 'myscript.js'] },
run_at: 'document_start'
},
{
name: 'anotherRule',
matches: ['http://www.bar.com/*'],
js: { code: "document.body.style.backgroundColor = 'red';" },
run_at: 'document_end'
}]);
...
// Navigates webview.
webview.src = 'http://www.foo.com';
You can defer addContentScripts call until you needs to inject scripts.
The following example shows how to overwrite an existing rule.
webview.addContentScripts([{
name: 'rule',
matches: ['http://www.foo.com/*'],
js: { files: ['scriptA.js'] },
run_at: 'document_start'}]);
// Do something.
webview.src = 'http://www.foo.com/*';
...
// Overwrite 'rule' defined before.
webview.addContentScripts([{
name: 'rule',
matches: ['http://www.bar.com/*'],
js: { files: ['scriptB.js'] },
run_at: 'document_end'}]);
If webview
has been naviagted to the origin (e.g., foo.com) and calls webview.addContentScripts
to add 'myRule', you need to wait for next navigation to make the scripts injected. If you want immediate injection, executeScript
will do the right thing.
Rules are preserved even if the guest process crashes or is killed or even if the webview
is reparented.
Refer to the content scripts documentation for more details.
Parameters | ||
---|---|---|
array of ContentScriptDetails | contentScriptList |
Details of the content scripts to add. |
back
<webview>.back(function callback)
Navigates backward one history entry if possible. Equivalent to go(-1)
.
Parameters | |||||
---|---|---|---|---|---|
function | (optional) callback |
Called after the navigation has either failed or completed successfully. If you specify the callback parameter, it should be a function that looks like this: function(boolean success) {...};
|
canGoBack
boolean <webview>.canGoBack()
Indicates whether or not it is possible to navigate backward through history. The state of this function is cached, and updated before each loadcommit
, so the best place to call it is on loadcommit
.
canGoForward
boolean <webview>.canGoForward()
Indicates whether or not it is possible to navigate forward through history. The state of this function is cached, and updated before each loadcommit
, so the best place to call it is on loadcommit
.
clearData
<webview>.clearData( ClearDataOptions options, ClearDataTypeSet types, function callback)
Clears browsing data for the webview
partition.
Parameters | ||
---|---|---|
ClearDataOptions | options |
Options determining which 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.style.backgroundColor = '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(function callback)
Navigates forward one history entry if possible. Equivalent to go(1)
.
Parameters | |||||
---|---|---|---|---|---|
function | (optional) callback |
Called after the navigation has either failed or completed successfully. If you specify the callback parameter, it should be a function that looks like this: function(boolean success) {...};
|
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.
getZoom
<webview>.getZoom(function callback)
Gets the current zoom factor.
Parameters | |||||
---|---|---|---|---|---|
function | callback |
Called after the current zoom factor is retrieved. The callback parameter should be a function that looks like this: function(double zoomFactor) {...};
|
getZoomMode
<webview>.getZoomMode(function callback)
go
<webview>.go(integer relativeIndex, function callback)
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 |
|||
function | (optional) callback |
Called after the navigation has either failed or completed successfully. If you specify the callback parameter, it should be a function that looks like this: function(boolean success) {...};
|
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.
<webview>.print()
Prints the contents of the webview
. This is equivalent to calling scripted print function from the webview
itself.
reload
<webview>.reload()
Reloads the current top-level page.
removeContentScripts
<webview>.removeContentScripts(array of string scriptNameList)
Since Chrome 44.
Removes content scripts from a webview
.
The following example removes "myRule" which was added before.
webview.removeContentScripts(['myRule']);
You can remove all the rules by calling:
webview.removeContentScripts();
Parameters | ||
---|---|---|
array of string | (optional) scriptNameList |
A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the |
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. |
setZoom
<webview>.setZoom(double zoomFactor, function callback)
Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see webviewTag.ZoomMode).
Parameters | ||
---|---|---|
double | zoomFactor |
The new zoom factor. |
function | (optional) callback |
Called after the page has been zoomed. If you specify the callback parameter, it should be a function that looks like this: function() {...}; |
setZoomMode
<webview>.setZoomMode( ZoomMode ZoomMode, function callback)
Since Chrome 43.
Sets the zoom mode of the webview
.
Parameters | ||
---|---|---|
ZoomMode | ZoomMode |
Defines how zooming is handled in the |
function | (optional) callback |
Called after the zoom mode has been changed. If you specify the callback parameter, it should be a function that looks like this: function() {...}; |
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. |
loadDataWithBaseUrl
<webview>.loadDataWithBaseUrl(string dataUrl, string baseUrl, string virtualUrl)
Since Chrome 40.
Loads a data URL with a specified base URL used for relative links. Optionally, a virtual URL can be provided to be shown to the user instead of the data URL.
Parameters | ||
---|---|---|
string | dataUrl |
The data URL to load. |
string | baseUrl |
The base URL that will be used for relative links. |
string | (optional) virtualUrl |
The URL that will be displayed to the user (in the address bar). |
setSpatialNavigationEnabled
<webview>.setSpatialNavigationEnabled(boolean enabled)
Since Chrome 71.
Sets spatial navigation state of the webview.
Parameters | ||
---|---|---|
boolean | enabled |
Spatial navigation state value. |
isSpatialNavigationEnabled
<webview>.isSpatialNavigationEnabled(function callback)
Since Chrome 71.
Queries whether spatial navigation is enabled for the webview.
Parameters | |||||
---|---|---|---|---|---|
function | callback |
The callback parameter should be a function that looks like this: function(boolean enabled) {...};
|
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
Listeners can be added for these events using the standard HTML addEventListener API. Listeners receive a customEvent
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);
});
Event object properties | ||
---|---|---|
integer | level |
The severity level of the log message. Ranges from -1 to 2. LOG_VERBOSE (console.debug) = -1, LOG_INFO (console.log, console.info) = 0, LOG_WARNING (console.warn) = 1, LOG_ERROR (console.error) = 2. |
string | message |
The logged message contents. |
integer | line |
The line number of the message source. |
string | sourceId |
A string identifying the resource which logged the message. |
contentload
Fired when the guest window fires a load
event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads.
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.
Event object properties | ||
---|---|---|
enum of "alert" , "confirm" , or "prompt" |
messageType |
The type of modal dialog requested by the guest. |
string | messageText |
The text the guest attempted to display in the modal dialog. |
DialogController | dialog |
An interface that can be used to respond to the guest's modal request. |
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!';
}
});
Event object properties | ||
---|---|---|
integer | processID |
Chrome's internal ID of the process that exited. |
enum of "normal" , "abnormal" , "crash" , or "kill" |
reason |
String indicating the reason for the exit. |
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.
Event object properties | ||
---|---|---|
string | searchText |
The string that is being searched for in the page. |
integer | numberOfMatches |
The number of matches found for |
integer | activeMatchOrdinal |
The ordinal number of the current active match, if it has been found. This will be |
SelectionRect | selectionRect |
Describes a rectangle around the active match, if it has been found, in screen coordinates. |
boolean | canceled |
Indicates whether the find request was canceled. |
string | finalUpdate |
Indicates that all find requests have completed and that no more |
loadabort
Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented.
Note: When a resource load is aborted, a loadabort
event will eventually be followed by a loadstop
event, even if all committed loads since the last loadstop
event (if any) were aborted.
Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort
will be fired and then the webview
will be navigated to 'about:blank'.
Event object properties | ||
---|---|---|
string | url |
Requested URL. |
boolean | isTopLevel |
Whether the load was top-level or in a subframe. |
integer | code |
Unique integer ID for the type of abort. Note that this ID is not guaranteed to remain backwards compatible between releases. You must not act based upon this specific integer. |
enum of "ERR_ABORTED" , "ERR_INVALID_URL" , "ERR_DISALLOWED_URL_SCHEME" , "ERR_BLOCKED_BY_CLIENT" , "ERR_ADDRESS_UNREACHABLE" , "ERR_EMPTY_RESPONSE" , "ERR_FILE_NOT_FOUND" , or "ERR_UNKNOWN_URL_SCHEME" |
reason |
String indicating what type of abort occurred. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. It is also possible that, in some cases, an error not listed here could be reported. |
loadcommit
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.
Event object properties | ||
---|---|---|
string | url |
The URL that committed. |
boolean | isTopLevel |
Whether the load is top-level or in a subframe. |
loadredirect
Fired when a top-level load request has redirected to a different URL.
Event object properties | ||
---|---|---|
string | oldUrl |
The requested URL before the redirect. |
string | newUrl |
The new URL after the redirect. |
boolean | isTopLevel |
Whether or not the redirect happened at top-level or in a subframe. |
loadstart
Fired when a load has begun.
Event object properties | ||
---|---|---|
string | url |
Requested URL. |
boolean | isTopLevel |
Whether the load is top-level or in a subframe. |
loadstop
Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop
already fired once) creates a new iframe which loads a page, then a second loadstop
will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.
Note: When a committed load is aborted, a loadstop
event will eventually follow a loadabort
event, even if all committed loads since the last loadstop
event (if any) were aborted.
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);
});
Event object properties | ||
---|---|---|
NewWindow | window |
An interface that can be used to either attach the requested target page to an existing |
string | targetUrl |
The target URL requested for the new window. |
double | initialWidth |
The initial width requested for the new window. |
double | initialHeight |
The initial height requested for the new window. |
string | name |
The requested name of the new window. |
enum of "ignore" , "save_to_disk" , "current_tab" , "new_background_tab" , "new_foreground_tab" , "new_window" , or "new_popup" |
windowOpenDisposition |
The requested disposition of the new window. |
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();
}
});
Event object properties | ||
---|---|---|
enum of "media" , "geolocation" , "pointerLock" , "download" , "loadplugin" , "filesystem" , or "fullscreen" |
permission |
The type of permission being requested. |
object | request |
An object which holds details of the requested permission. Depending on the type of permission requested, this may be a webviewTag.MediaPermissionRequest, webviewTag.GeolocationPermissionRequest, webviewTag.PointerLockPermissionRequest, webviewTag.DownloadPermissionRequest, webviewTag.LoadPluginPermissionRequest, or webviewTag.FullscreenPermissionRequest. |
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';
});
Event object properties | ||
---|---|---|
integer | processID |
Chrome's internal ID of the process that became responsive. |
sizechanged
Fired when the embedded web content has been resized via autosize
. Only fires if autosize
is enabled.
Event object properties | ||
---|---|---|
double | oldWidth |
Old width of embedded web content. |
double | oldHeight |
Old height of embedded web content. |
double | newWidth |
New width of embedded web content. |
double | newHeight |
New height of embedded web content. |
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.
Event object properties | ||
---|---|---|
integer | processID |
Chrome's internal ID of the process that has become unresponsive. |
zoomchange
Fired when the page's zoom changes.
Event object properties | ||
---|---|---|
double | oldZoomFactor |
The page's previous zoom factor. |
double | newZoomFactor |
The new zoom factor that the page was zoomed to. |