<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 "clear", "keep", or "activate" action)
terminate <webview>.terminate()
DOM Events
close
consolemessage
contentload
dialog
exit
findupdate
loadabort
loadcommit
loadredirect
loadstart
loadstop
newwindow
permissionrequest
responsive
sizechanged
unresponsive

Types

ClearDataOptions

Options that determine what data should be cleared by clearData.
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

A set of data types. Missing properties are interpreted as false.
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

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.

ContentWindow

Messaging handle to a guest window.
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 event.source on the message event it receives.

This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a message event listener to its own frame.

Parameters
any message Message object to send to the guest.
string targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched.

DialogController

Interface attached to dialog DOM events.
methods

ok

DialogController.ok(string response)

Accept the dialog. Equivalent to clicking OK in an alert, confirm, or prompt dialog.

Parameters
string (optional) response The response string to provide to the guest when accepting a prompt dialog.

cancel

DialogController.cancel()

Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog.

FindCallbackResults

Contains all of the results of the find request.
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

Options for the find request.
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

Interface attached to newwindow DOM events.
methods

attach

NewWindow.attach(object webview)

Attach the requested target page to an existing webview element.

Parameters
object webview The webview element to which the target page should be attached.

discard

NewWindow.discard()

Cancel the new window request.

MediaPermissionRequest

The type of request object which accompanies a media permissionrequest DOM event.
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 allow is not called.

GeolocationPermissionRequest

The type of request object which accompanies a geolocation permissionrequest DOM event.
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 allow is not called.

PointerLockPermissionRequest

The type of request 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

allow

PointerLockPermissionRequest.allow()

Allow the permission request.

deny

PointerLockPermissionRequest.deny()

Deny the permission request. This is the default behavior if allow is not called.

DownloadPermissionRequest

The type of request object which accompanies a download permissionrequest DOM event.
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 allow is not called.

LoadPluginPermissionRequest

The type of request object which accompanies a loadplugin permissionrequest DOM event.

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 is not called..

deny

LoadPluginPermissionRequest.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.

WebRequestEventInteface

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.

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.

Note that conditions and actions for declarative webview webRequests should be instantiated from their 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]);

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) {...};
array of any (optional) result The result of the script in every injected frame.

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) {...};
FindCallbackResults (optional) results Contains all of the results of the find request. results can be omitted if it is not utilized in the callback function body; for example, if the callback is only used to discern when the find request has completed.

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

Listeners can be added for these events using the standard HTML addEventListener API. Listeners receive a custom 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);
});

integer level The severity level of the log message. Ranges from 0 to 4. 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.

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.

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!';
  }
});

integer processID Chrome's interal 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.

string searchText The string that is being searched for in the page. integer numberOfMatches The number of matches found for searchText on the page so far. integer activeMatchOrdinal The ordinal number of the current active match, if it has been found. This will be 0 until then. 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 findupdate events will be fired until more find requests are made.

loadabort

Fired when a top-level load has aborted without committing.

string url Requested URL. boolean isTopLevel Whether the load was top-level or in a subframe. enum of "networkError", "download", "canceled", "sslError", or "safeBrowsingError" reason String indicating what type of abort occurred.

loadcommit

Fired when a load has committed.

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.

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.

string url Requested URL. boolean isTopLevel Whether the load is top-level or in a subframe.

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);
});

NewWindow window An interface that can be used to either attach the requested target page to an existing webview element or explicitly discard the request. 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();
  }
});

enum of "media", "geolocation", "pointerLock", "download", or "loadplugin" permission The type of permission being requested. integer requestId A number which uniquely identifies this request from the guest. 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, or webviewTag.LoadPluginPermissionRequest.

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';
});

integer processID Chrome's internal ID of the process that became responsive.

sizechanged

Fired when the embedded web content has been resized. Only fires if autosize is enabled.

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.

integer processID Chrome's internal ID of the process that has become unresponsive.