chrome.webviewTag
- 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 thewebview
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). - Permissions
webview
Summary
- Types
- Properties
- Methods
webviewTag.addContentScripts(contentScriptList: ContentScriptDetails[])
webviewTag.back(callback: function)
webviewTag.canGoBack(): boolean
webviewTag.canGoForward(): boolean
webviewTag.captureVisibleRegion(options?: extensionTypes.ImageDetails, callback: function)
webviewTag.clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback: function)
webviewTag.executeScript(details: InjectDetails, callback: function)
webviewTag.find(searchText: string, options: FindOptions, callback: function)
webviewTag.forward(callback: function)
webviewTag.getAudioState(callback: function)
webviewTag.getProcessId(): number
webviewTag.getUserAgent(): string
webviewTag.getZoom(callback: function)
webviewTag.getZoomMode(callback: function)
webviewTag.go(relativeIndex: number, callback: function)
webviewTag.insertCSS(details: InjectDetails, callback: function)
webviewTag.isAudioMuted(callback: function)
webviewTag.isSpatialNavigationEnabled(callback: function)
webviewTag.isUserAgentOverridden()
webviewTag.loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl: string)
webviewTag.print()
webviewTag.reload()
webviewTag.removeContentScripts(scriptNameList: string[])
webviewTag.setAudioMuted(mute: boolean)
webviewTag.setSpatialNavigationEnabled(enabled: boolean)
webviewTag.setUserAgentOverride(userAgent: string)
webviewTag.setZoom(zoomFactor: number, callback: function)
webviewTag.setZoomMode(ZoomMode: ZoomMode, callback: function)
webviewTag.stop()
webviewTag.stopFinding(action: enum)
webviewTag.terminate()
- Events
Types
ClearDataOptions
Options that determine what data should be cleared by clearData
.
Properties
- sincenumber optional
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 to0
(which would remove all browsing data).
ClearDataTypeSet
A set of data types. Missing properties are interpreted as false
.
Properties
- appcacheboolean optional
Websites' appcaches.
- cacheboolean optional
Since Chrome 44.
Since Chrome 43.
The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. - cookiesboolean optional
The partition's cookies.
- fileSystemsboolean optional
Websites' filesystems.
- indexedDBboolean optional
Websites' IndexedDB data.
- localStorageboolean optional
Websites' local storage data.
- persistentCookiesboolean optional
Since Chrome 58.
The partition's persistent cookies.
- sessionCookiesboolean optional
Since Chrome 58.
The partition's session cookies.
- webSQLboolean optional
Websites' WebSQL data.
ContentScriptDetails
Since Chrome 44.
Details of the content script to inject. Refer to the content scripts documentation for more details.
Properties
- all_framesboolean optional
If
all_frames
istrue
, this implies that the JavaScript or CSS should be injected into all frames of current page. By default,all_frames
isfalse
and the JavaScript or CSS is only injected into the top frame. - cssInjectionItems optional
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.
- exclude_globsstring[] optional
Applied after matches to exclude URLs that match this glob. Intended to emulate the @exclude Greasemonkey keyword.
- exclude_matchesstring[] optional
Excludes pages that this content script would otherwise be injected into.
- include_globsstring[] optional
Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword.
- jsInjectionItems optional
The JavaScript code or a list of JavaScript files to be injected into matching pages. These are injected in the order they appear.
- match_about_blankboolean optional
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.
- matchesstring[]
Specifies which pages this content script will be injected into.
- namestring
The name of the content script to inject.
- run_atcontentScripts.RunAt optional
The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle".
ContentWindow
Messaging handle to a guest window.
Properties
- postMessagefunction
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.The postMessage function looks like this:
postMessage(message: any, targetOrigin: string) => {...}
- messageany
Message object to send to the guest.
- targetOriginstring
Specifies what the origin of the guest window must be for the event to be dispatched.
ContextMenuCreateProperties
Since Chrome 44.
Properties
- checkedboolean optional
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.
- contextsContextType[] optional
List of contexts this menu item will appear in. Defaults to ['page'] if not specified.
- documentUrlPatternsstring[] optional
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.
- enabledboolean optional
Whether this context menu item is enabled or disabled. Defaults to
true
. - idstring optional
The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.
- onclickfunction optional
A function that will be called back when the menu item is clicked.
The onclick function looks like this:
onclick(info: object) => {...}
- infoobject
- parentIdenum optional
The ID of a parent menu item; this makes the item a child of a previously added item.
- targetUrlPatternsstring[] optional
Similar to documentUrlPatterns, but lets you filter based on the
src
attribute of img/audio/video tags and thehref
of anchor tags. - titlestring optional
The text to be displayed in the item; this is required unless
type
is 'separator'. When the context is 'selection', you can use%s
within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin". - typecontextMenus.ItemType optional
The type of menu item. Defaults to 'normal' if not specified.
ContextMenuUpdateProperties
Since Chrome 44.
Properties
- checkedboolean optional
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.
- contextsContextType[] optional
List of contexts this menu item will appear in.
- documentUrlPatternsstring[] optional
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.
- enabledboolean optional
Whether this context menu item is enabled or disabled.
- onclickfunction optional
A function that will be called back when the menu item is clicked.
The onclick function looks like this:
onclick(info: object) => {...}
- infoobject
- parentIdenum optional
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.
- targetUrlPatternsstring[] optional
Similar to documentUrlPatterns, but lets you filter based on the
src
attribute of img/audio/video tags and thehref
of anchor tags. - titlestring optional
The text to be displayed in the item
- typecontextMenus.ItemType optional
The type of menu item.
ContextMenus
Since Chrome 44.
Properties
- onShowevents.Event<function>
Fired before showing a context menu on this
webview
. Can be used to disable this context menu by callingevent.preventDefault()
.Add a listener like this:
onShow.addListener(listener)
- listenerfunction
The listener parameter should be a function that looks like this:
(event: object) => {...}
- eventobject
- preventDefaultfunction
Call this to prevent showing the context menu.
The preventDefault function looks like this:
preventDefault() => {...}
- createfunction
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
).The create function looks like this:
create(createProperties: ContextMenuCreateProperties, callback: function): enum => {...}
- createProperties
The properties used to create the item
- callbackfunction
Called when the item has been created in the browser. If there were any problems creating the item, details will be available in
runtime.lastError
.The callback parameter should be a function that looks like this:
() => {...}
- returnsenum
The ID of the newly created item.
- removefunction
Removes a context menu item.
The remove function looks like this:
remove(menuItemId: enum, callback: function) => {...}
- menuItemIdenum
The ID of the context menu item to remove.
- callbackfunction
Called when the context menu has been removed.
The callback parameter should be a function that looks like this:
() => {...}
- removeAllfunction
Removes all context menu items added to this
webview
.The removeAll function looks like this:
removeAll(callback: function) => {...}
- callbackfunction
Called when removal is complete.
The callback parameter should be a function that looks like this:
() => {...}
- updatefunction
Updates a previously created context menu item.
The update function looks like this:
update(id: enum, updateProperties: ContextMenuUpdateProperties, callback: function) => {...}
- idenum
The ID of the item to update.
- updateProperties
The properties to update. Accepts the same values as the create function.
- callbackfunction
Called when the context menu has been updated.
The callback parameter should be a function that looks like this:
() => {...}
DialogController
Interface attached to dialog
DOM events.
Properties
- cancelfunction
Reject the dialog. Equivalent to clicking Cancel in a
confirm
orprompt
dialog.The cancel function looks like this:
cancel() => {...}
- okfunction
Accept the dialog. Equivalent to clicking OK in an
alert
,confirm
, orprompt
dialog.The ok function looks like this:
ok(response: string) => {...}
- responsestring
The response string to provide to the guest when accepting a
prompt
dialog.
DownloadPermissionRequest
The type of request
object which accompanies a download
permissionrequest
DOM event.
Properties
- requestMethodstring
The HTTP request type (e.g.
GET
) associated with the download request. - urlstring
The requested download URL.
- allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request. This is the default behavior if
allow
is not called.The deny function looks like this:
deny() => {...}
FileSystemPermissionRequest
The type of request
object which accompanies a filesystem
permissionrequest
DOM event.
Properties
- urlstring
The URL of the frame requesting access to local file system.
- allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request.
The deny function looks like this:
deny() => {...}
FindCallbackResults
Contains all of the results of the find request.
Properties
- activeMatchOrdinalnumber
The ordinal number of the current match.
- canceledboolean
Indicates whether this find request was canceled.
- numberOfMatchesnumber
The number of times
searchText
was matched on the page. - selectionRect
Describes a rectangle around the active match in screen coordinates.
FindOptions
Options for the find request.
Properties
- backwardboolean optional
Flag to find matches in reverse order. The default value is
false
. - matchCaseboolean optional
Flag to match with case-sensitivity. The default value is
false
.
FullscreenPermissionRequest
Since Chrome 43.
The type of request
object which accompanies a fullscreen
permissionrequest
DOM event.
Properties
- originstring
The origin of the frame inside the
webview
that initiated the fullscreen request. - allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request.
The deny function looks like this:
deny() => {...}
GeolocationPermissionRequest
The type of request
object which accompanies a geolocation
permissionrequest
DOM event.
Properties
- urlstring
The URL of the frame requesting access to geolocation data.
- allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request. This is the default behavior if
allow
is not called.The deny function looks like this:
deny() => {...}
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
- codestring optional
JavaScript or CSS code to inject.
Warning:
Be careful using thecode
parameter. Incorrect use of it may open your app to cross site scripting attacks. - filestring optional
JavaScript or CSS file to inject.
InjectionItems
Since Chrome 44.
The type of injection item: code or a set of files.
Properties
- codestring optional
JavaScript code or CSS to be injected into matching pages.
- filesstring[] optional
The list of JavaScript or CSS files to be injected into matching pages. These are injected in the order they appear in this array.
LoadPluginPermissionRequest
The type of request
object which accompanies a loadplugin
permissionrequest
DOM event.
Properties
- identifierstring
The plugin's identifier string.
- namestring
The plugin's display name.
- allowfunction
Allow the permission request. This is the default behavior if
deny
is not called..The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request.
The deny function looks like this:
deny() => {...}
MediaPermissionRequest
The type of request
object which accompanies a media
permissionrequest
DOM event.
Properties
- urlstring
The URL of the frame requesting access to user media.
- allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request. This is the default behavior if
allow
is not called.The deny function looks like this:
deny() => {...}
NewWindow
Interface attached to newwindow
DOM events.
Properties
- attachfunction
Attach the requested target page to an existing
webview
element.The attach function looks like this:
attach(webview: object) => {...}
- webviewobject
The
webview
element to which the target page should be attached.
- discardfunction
Cancel the new window request.
The discard function looks like this:
discard() => {...}
PointerLockPermissionRequest
The type of request
object which accompanies a pointerLock
permissionrequest
DOM event.
Properties
- lastUnlockedBySelfboolean
Whether or not the requesting frame was the most recent client to hold pointer lock.
- urlstring
The URL of the frame requesting pointer lock.
- userGestureboolean
Whether or not pointer lock was requested as a result of a user input gesture.
- allowfunction
Allow the permission request.
The allow function looks like this:
allow() => {...}
- denyfunction
Deny the permission request. This is the default behavior if
allow
is not called.The deny function looks like this:
deny() => {...}
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
- heightnumber
Height of the rectangle.
- leftnumber
Distance from the left edge of the screen to the left edge of the rectangle.
- topnumber
Distance from the top edge of the screen to the top edge of the rectangle.
- widthnumber
Width 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.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]);
ContextType
Since Chrome 44.
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"
ZoomMode
Since Chrome 43.
Defines the how zooming is handled in the webview
.
Enum
"per-origin"
, "per-view"
, or "disabled"
Properties
contentWindow
Object reference which can be used to post messages into the guest page.
Type
contextMenus
Since Chrome 44.
Similar to chrome's ContextMenus API, but applies to webview
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.
Type
request
Interface which provides access to webRequest events on the guest page.
Methods
addContentScripts
webviewTag.addContentScripts(contentScriptList: ContentScriptDetails[])
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
- contentScriptList
Details of the content scripts to add.
back
webviewTag.back(callback: function)
Navigates backward one history entry if possible. Equivalent to go(-1)
.
Parameters
- callbackfunction
Since Chrome 44.
Called after the navigation has either failed or completed successfully.
The callback parameter should be a function that looks like this:
(success: boolean) => {...}
- successboolean
Indicates whether the navigation was successful.
canGoBack
webviewTag.canGoBack(): boolean
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
.
Returns
- returnsboolean
canGoForward
webviewTag.canGoForward(): boolean
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
.
Returns
- returnsboolean
captureVisibleRegion
webviewTag.captureVisibleRegion(options?: extensionTypes.ImageDetails, callback: function)
Since Chrome 50.
Captures the visible region of the webview.
Parameters
- optionsextensionTypes.ImageDetails optional
- callbackfunction
The callback parameter should be a function that looks like this:
(dataUrl: string) => {...}
- dataUrlstring
A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display.
clearData
webviewTag.clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback: function)
Clears browsing data for the webview
partition.
Parameters
- options
Options determining which data to clear.
- types
The types of data to be cleared.
- callbackfunction
Called after the data has been successfully cleared.
The callback parameter should be a function that looks like this:
() => {...}
executeScript
webviewTag.executeScript(details: InjectDetails, callback: function)
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
- details
Details of the script to run.
- callbackfunction
Called after all the JavaScript has been executed.
The callback parameter should be a function that looks like this:
(result: any[]) => {...}
- resultany[]
The result of the script in every injected frame.
find
webviewTag.find(searchText: string, options: FindOptions, callback: function)
Initiates a find-in-page request.
Parameters
- searchTextstring
The string to find in the page.
- options
Options for the find request.
- callbackfunction
Called after all find results have been returned for this find request.
The callback parameter should be a function that looks like this:
(results: FindCallbackResults) => {...}
- 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
webviewTag.forward(callback: function)
Navigates forward one history entry if possible. Equivalent to go(1)
.
Parameters
- callbackfunction
Since Chrome 44.
Called after the navigation has either failed or completed successfully.
The callback parameter should be a function that looks like this:
(success: boolean) => {...}
- successboolean
Indicates whether the navigation was successful.
getAudioState
webviewTag.getAudioState(callback: function)
Since Chrome 62.
Queries audio state.
Parameters
- callbackfunction
The callback parameter should be a function that looks like this:
(audible: boolean) => {...}
- audibleboolean
getProcessId
webviewTag.getProcessId(): number
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.
Returns
- returnsnumber
getUserAgent
webviewTag.getUserAgent(): string
Returns the user agent string used by the webview
for guest page requests.
Returns
- returnsstring
getZoom
webviewTag.getZoom(callback: function)
Gets the current zoom factor.
Parameters
- callbackfunction
Called after the current zoom factor is retrieved.
The callback parameter should be a function that looks like this:
(zoomFactor: number) => {...}
- zoomFactornumber
The current zoom factor.
getZoomMode
webviewTag.getZoomMode(callback: function)
Since Chrome 43.
Gets the current zoom mode.
go
webviewTag.go(relativeIndex: number, callback: function)
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
- relativeIndexnumber
Relative history index to which the
webview
should be navigated. For example, a value of2
will navigate forward 2 history entries if possible; a value of-3
will navigate backward 3 entries. - callbackfunction
Since Chrome 40.
Called after the navigation has either failed or completed successfully.
The callback parameter should be a function that looks like this:
(success: boolean) => {...}
- successboolean
Indicates whether the navigation was successful.
insertCSS
webviewTag.insertCSS(details: InjectDetails, callback: function)
Injects CSS into the guest page.
Parameters
- details
Details of the CSS to insert.
- callbackfunction
Called after the CSS has been inserted.
The callback parameter should be a function that looks like this:
() => {...}
isAudioMuted
webviewTag.isAudioMuted(callback: function)
Since Chrome 62.
Queries whether audio is muted.
Parameters
- callbackfunction
The callback parameter should be a function that looks like this:
(muted: boolean) => {...}
- mutedboolean
isSpatialNavigationEnabled
webviewTag.isSpatialNavigationEnabled(callback: function)
Since Chrome 71.
Queries whether spatial navigation is enabled for the webview.
Parameters
- callbackfunction
The callback parameter should be a function that looks like this:
(enabled: boolean) => {...}
- enabledboolean
isUserAgentOverridden
webviewTag.isUserAgentOverridden()
Indicates whether or not the webview
's user agent string has been overridden by setUserAgentOverride
.
loadDataWithBaseUrl
webviewTag.loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl: string)
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
- dataUrlstring
The data URL to load.
- baseUrlstring
The base URL that will be used for relative links.
- virtualUrlstring
The URL that will be displayed to the user (in the address bar).
webviewTag.print()
Prints the contents of the webview
. This is equivalent to calling scripted print function from the webview
itself.
reload
webviewTag.reload()
Reloads the current top-level page.
removeContentScripts
webviewTag.removeContentScripts(scriptNameList: string[])
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
- scriptNameListstring[]
A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the
webview
will be removed.
setAudioMuted
webviewTag.setAudioMuted(mute: boolean)
Since Chrome 62.
Sets audio mute state of the webview.
Parameters
- muteboolean
Mute audio value
setSpatialNavigationEnabled
webviewTag.setSpatialNavigationEnabled(enabled: boolean)
Since Chrome 71.
Sets spatial navigation state of the webview.
Parameters
- enabledboolean
Spatial navigation state value.
setUserAgentOverride
webviewTag.setUserAgentOverride(userAgent: string)
Override the user agent string used by the webview
for guest page requests.
Parameters
- userAgentstring
The user agent string to use.
setZoom
webviewTag.setZoom(zoomFactor: number, callback: function)
Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see ZoomMode
).
Parameters
- zoomFactornumber
The new zoom factor.
- callbackfunction
Called after the page has been zoomed.
The callback parameter should be a function that looks like this:
() => {...}
setZoomMode
webviewTag.setZoomMode(ZoomMode: ZoomMode, callback: function)
Since Chrome 43.
Sets the zoom mode of the webview
.
Parameters
- ZoomMode
Defines how zooming is handled in the
webview
. - callbackfunction
Called after the zoom mode has been changed.
The callback parameter should be a function that looks like this:
() => {...}
stop
webviewTag.stop()
Stops loading the current webview
navigation if in progress.
stopFinding
webviewTag.stopFinding(action: enum)
Ends the current find session (clearing all highlighting) and cancels all find requests in progress.
Parameters
- actionenum
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 iskeep
.
terminate
webviewTag.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.
Events
close
webviewTag.close.addListener(listener: function)
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'; });
Event
- listenerfunction
The listener parameter should be a function that looks like this:
() => {...}
consolemessage
webviewTag.consolemessage.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(level: number, message: string, line: number, sourceId: string) => {...}
- levelnumber
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.
- messagestring
The logged message contents.
- linenumber
The line number of the message source.
- sourceIdstring
A string identifying the resource which logged the message.
contentload
webviewTag.contentload.addListener(listener: function)
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"' }); });
Event
- listenerfunction
The listener parameter should be a function that looks like this:
() => {...}
dialog
webviewTag.dialog.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(messageType: enum, messageText: string, dialog: DialogController) => {...}
- messageTypeenum
The type of modal dialog requested by the guest.
- messageTextstring
The text the guest attempted to display in the modal dialog.
- dialog
An interface that can be used to respond to the guest's modal request.
exit
webviewTag.exit.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(processID: number, reason: enum) => {...}
- processIDnumber
Chrome's internal ID of the process that exited.
- reasonenum
String indicating the reason for the exit.
findupdate
webviewTag.findupdate.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(searchText: string, numberOfMatches: number, activeMatchOrdinal: number, selectionRect: SelectionRect, canceled: boolean, finalUpdate: string) => {...}
- searchTextstring
The string that is being searched for in the page.
- numberOfMatchesnumber
The number of matches found for
searchText
on the page so far. - activeMatchOrdinalnumber
The ordinal number of the current active match, if it has been found. This will be
0
until then. - selectionRect
Describes a rectangle around the active match, if it has been found, in screen coordinates.
- canceledboolean
Indicates whether the find request was canceled.
- finalUpdatestring
Indicates that all find requests have completed and that no more
findupdate
events will be fired until more find requests are made.
loadabort
webviewTag.loadabort.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(url: string, isTopLevel: boolean, code: number, reason: enum) => {...}
- urlstring
Requested URL.
- isTopLevelboolean
Whether the load was top-level or in a subframe.
- codenumber
Since Chrome 44.
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.
- reasonenum
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
webviewTag.loadcommit.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(url: string, isTopLevel: boolean) => {...}
- urlstring
The URL that committed.
- isTopLevelboolean
Whether the load is top-level or in a subframe.
loadredirect
webviewTag.loadredirect.addListener(listener: function)
Fired when a top-level load request has redirected to a different URL.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(oldUrl: string, newUrl: string, isTopLevel: boolean) => {...}
- oldUrlstring
The requested URL before the redirect.
- newUrlstring
The new URL after the redirect.
- isTopLevelboolean
Whether or not the redirect happened at top-level or in a subframe.
loadstart
webviewTag.loadstart.addListener(listener: function)
Fired when a load has begun.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(url: string, isTopLevel: boolean) => {...}
- urlstring
Requested URL.
- isTopLevelboolean
Whether the load is top-level or in a subframe.
loadstop
webviewTag.loadstop.addListener(listener: function)
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.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
() => {...}
newwindow
webviewTag.newwindow.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(window: NewWindow, targetUrl: string, initialWidth: number, initialHeight: number, name: string, windowOpenDisposition: enum) => {...}
- window
An interface that can be used to either attach the requested target page to an existing
webview
element or explicitly discard the request. - targetUrlstring
The target URL requested for the new window.
- initialWidthnumber
The initial width requested for the new window.
- initialHeightnumber
The initial height requested for the new window.
- namestring
The requested name of the new window.
- windowOpenDispositionenum
The requested disposition of the new window.
permissionrequest
webviewTag.permissionrequest.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(permission: enum, request: object) => {...}
- permissionenum
The type of permission being requested.
- requestobject
An object which holds details of the requested permission. Depending on the type of permission requested, this may be a
MediaPermissionRequest
,GeolocationPermissionRequest
,PointerLockPermissionRequest
,DownloadPermissionRequest
,LoadPluginPermissionRequest
, orFullscreenPermissionRequest
.
responsive
webviewTag.responsive.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(processID: number) => {...}
- processIDnumber
Chrome's internal ID of the process that became responsive.
sizechanged
webviewTag.sizechanged.addListener(listener: function)
Fired when the embedded web content has been resized via autosize
. Only fires if autosize
is enabled.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(oldWidth: number, oldHeight: number, newWidth: number, newHeight: number) => {...}
- oldWidthnumber
Old width of embedded web content.
- oldHeightnumber
Old height of embedded web content.
- newWidthnumber
New width of embedded web content.
- newHeightnumber
New height of embedded web content.
unresponsive
webviewTag.unresponsive.addListener(listener: function)
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
- listenerfunction
The listener parameter should be a function that looks like this:
(processID: number) => {...}
- processIDnumber
Chrome's internal ID of the process that has become unresponsive.
zoomchange
webviewTag.zoomchange.addListener(listener: function)
Fired when the page's zoom changes.
Event
- listenerfunction
The listener parameter should be a function that looks like this:
(oldZoomFactor: number, newZoomFactor: number) => {...}
- oldZoomFactornumber
The page's previous zoom factor.
- newZoomFactornumber
The new zoom factor that the page was zoomed to.