欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples
欢迎 What's new in Chrome extensions Get help with Chrome extensions API reference Samples

chrome.webviewTag

This API is part of the deprecated Chrome Apps platform. Learn more about migrating your app.
  • 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).

  • Permissions
    webview

Summary

Types

ClearDataOptions

Options that determine what data should be cleared by clearData.

Properties

  • since

    number 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 to 0 (which would remove all browsing data).

ClearDataTypeSet

A set of data types. Missing properties are interpreted as false.

Properties

  • appcache

    boolean optional

    Websites' appcaches.

  • cache

    boolean optional

    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.

  • cookies

    boolean optional

    The partition's cookies.

  • fileSystems

    boolean optional

    Websites' filesystems.

  • indexedDB

    boolean optional

    Websites' IndexedDB data.

  • localStorage

    boolean optional

    Websites' local storage data.

  • persistentCookies

    boolean optional

    Chrome 58+

    The partition's persistent cookies.

  • sessionCookies

    boolean optional

    Chrome 58+

    The partition's session cookies.

  • webSQL

    boolean optional

    Websites' WebSQL data.

ContentScriptDetails

Chrome 44+

Details of the content script to inject. Refer to the content scripts documentation for more details.

Properties

  • all_frames

    boolean optional

    If all_frames is true, this implies that the JavaScript or CSS should be injected into all frames of current page. By default, all_frames is false and the JavaScript or CSS is only injected into the top frame.

  • css

    InjectionItems 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_globs

    string[] optional

    Applied after matches to exclude URLs that match this glob. Intended to emulate the @exclude Greasemonkey keyword.

  • exclude_matches

    string[] optional

    Excludes pages that this content script would otherwise be injected into.

  • include_globs

    string[] optional

    Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword.

  • js

    InjectionItems 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_blank

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

  • matches

    string[]

    Specifies which pages this content script will be injected into.

  • name

    string

    The name of the content script to inject.

  • run_at

    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

  • postMessage

    function

    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: (message: any, targetOrigin: string) => {...}

    • message

      any

      Message object to send to the guest.

    • targetOrigin

      string

      Specifies what the origin of the guest window must be for the event to be dispatched.

ContextMenuCreateProperties

Chrome 44+

Properties

  • checked

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

  • contexts

    [ContextType, ...ContextType[]] optional

    List of contexts this menu item will appear in. Defaults to ['page'] if not specified.

  • documentUrlPatterns

    string[] 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.

  • enabled

    boolean optional

    Whether this context menu item is enabled or disabled. Defaults to true.

  • id

    string optional

    The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.

  • parentId

    string | number optional

    The ID of a parent menu item; this makes the item a child of a previously added item.

  • targetUrlPatterns

    string[] optional

    Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags.

  • title

    string 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".

  • type

    ItemType optional

    The type of menu item. Defaults to 'normal' if not specified.

  • onclick

    function optional

    A function that will be called back when the menu item is clicked.

    The onclick function looks like: (info: OnClickData) => {...}

    • Information about the item clicked and the context where the click happened.

ContextMenus

Chrome 44+

Properties

  • onShow

    event

    Fired before showing a context menu on this webview. Can be used to disable this context menu by calling event.preventDefault().

    The onShow.addListener function looks like: (callback: function) => {...}

    • callback

      function

      The callback parameter looks like: (event: object) => void

      • event

        object

        • preventDefault

          function

          Call this to prevent showing the context menu.

          The preventDefault function looks like: () => {...}

  • create

    function

    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: (createProperties: object, callback?: function) => {...}

    • createProperties

      object

      The properties used to create the item

    • callback

      function optional

      The callback parameter looks like: () => void

    • returns

      string | number

      The ID of the newly created item.

  • remove

    function

    Removes a context menu item.

    The remove function looks like: (menuItemId: string | number, callback?: function) => {...}

    • menuItemId

      string | number

      The ID of the context menu item to remove.

    • callback

      function optional

      The callback parameter looks like: () => void

  • removeAll

    function

    Removes all context menu items added to this webview.

    The removeAll function looks like: (callback?: function) => {...}

    • callback

      function optional

      The callback parameter looks like: () => void

  • update

    function

    Updates a previously created context menu item.

    The update function looks like: (id: string | number, updateProperties: object, callback?: function) => {...}

    • id

      string | number

      The ID of the item to update.

    • updateProperties

      object

      The properties to update. Accepts the same values as the create function.

    • callback

      function optional

      The callback parameter looks like: () => void

ContextMenuUpdateProperties

Chrome 44+

Properties

  • checked

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

  • contexts

    [ContextType, ...ContextType[]] optional

    List of contexts this menu item will appear in.

  • documentUrlPatterns

    string[] 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.

  • enabled

    boolean optional

    Whether this context menu item is enabled or disabled.

  • parentId

    string | number 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.

  • targetUrlPatterns

    string[] optional

    Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags.

  • title

    string optional

    The text to be displayed in the item

  • type

    ItemType optional

    The type of menu item.

  • onclick

    function optional

    A function that will be called back when the menu item is clicked.

    The onclick function looks like: (info: OnClickData) => {...}

    • Information about the item clicked and the context where the click happened.

ContextType

Chrome 44+

The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts.

Type

"all"

,

"page"

,

"frame"

,

"selection"

,

"link"

,

"editable"

,

"image"

,

"video"

,
or

"audio"

DialogController

Interface attached to dialog DOM events.

Properties

  • cancel

    function

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

    The cancel function looks like: () => {...}

  • ok

    function

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

    The ok function looks like: (response?: string) => {...}

    • response

      string optional

      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

  • requestMethod

    string

    The HTTP request type (e.g. GET) associated with the download request.

  • url

    string

    The requested download URL.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

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

    The deny function looks like: () => {...}

FileSystemPermissionRequest

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

Properties

  • url

    string

    The URL of the frame requesting access to local file system.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

    Deny the permission request.

    The deny function looks like: () => {...}

FindCallbackResults

Contains all of the results of the find request.

Properties

  • activeMatchOrdinal

    number

    The ordinal number of the current match.

  • canceled

    boolean

    Indicates whether this find request was canceled.

  • numberOfMatches

    number

    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

  • backward

    boolean optional

    Flag to find matches in reverse order. The default value is false.

  • matchCase

    boolean optional

    Flag to match with case-sensitivity. The default value is false.

FullscreenPermissionRequest

Chrome 43+

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

Properties

  • origin

    string

    The origin of the frame inside the webview that initiated the fullscreen request.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

    Deny the permission request.

    The deny function looks like: () => {...}

GeolocationPermissionRequest

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

Properties

  • url

    string

    The URL of the frame requesting access to geolocation data.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

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

    The deny function looks like: () => {...}

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

  • code

    string optional

    JavaScript or CSS code to inject.

    Warning: Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks.

  • file

    string optional

    JavaScript or CSS file to inject.

InjectionItems

Chrome 44+

The type of injection item: code or a set of files.

Properties

  • code

    string optional

    JavaScript code or CSS to be injected into matching pages.

  • files

    string[] 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

  • identifier

    string

    The plugin's identifier string.

  • name

    string

    The plugin's display name.

  • allow

    function

    Allow the permission request. This is the default behavior if deny is not called..

    The allow function looks like: () => {...}

  • deny

    function

    Deny the permission request.

    The deny function looks like: () => {...}

MediaPermissionRequest

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

Properties

  • url

    string

    The URL of the frame requesting access to user media.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

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

    The deny function looks like: () => {...}

NewWindow

Interface attached to newwindow DOM events.

Properties

  • attach

    function

    Attach the requested target page to an existing webview element.

    The attach function looks like: (webview: object) => {...}

    • webview

      object

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

  • discard

    function

    Cancel the new window request.

    The discard function looks like: () => {...}

PointerLockPermissionRequest

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

Properties

  • lastUnlockedBySelf

    boolean

    Whether or not the requesting frame was the most recent client to hold pointer lock.

  • url

    string

    The URL of the frame requesting pointer lock.

  • userGesture

    boolean

    Whether or not pointer lock was requested as a result of a user input gesture.

  • allow

    function

    Allow the permission request.

    The allow function looks like: () => {...}

  • deny

    function

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

    The deny function looks like: () => {...}

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

  • height

    number

    Height of the rectangle.

  • left

    number

    Distance from the left edge of the screen to the left edge of the rectangle.

  • top

    number

    Distance from the top edge of the screen to the top edge of the rectangle.

  • width

    number

    Width of the rectangle.

WebRequestEventInterface

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

ZoomMode

Chrome 43+

Defines the how zooming is handled in the webview.

Type

"per-origin"

,

"per-view"

,
or

"disabled"

Properties

contentWindow

Object reference which can be used to post messages into the guest page.

contextMenus

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.

request

Interface which provides access to webRequest events on the guest page.

Methods

addContentScripts

chrome.webviewTag.addContentScripts(
  contentScriptList: [ContentScriptDetails, ...ContentScriptDetails[]],
)
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

back

chrome.webviewTag.back(
  callback?: function,
)

Navigates backward one history entry if possible. Equivalent to go(-1).

Parameters

  • callback

    function optional

    Chrome 44+

    The callback parameter looks like: (success: boolean) => void

    • success

      boolean

      Indicates whether the navigation was successful.

canGoBack

chrome.webviewTag.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.

Returns

  • boolean

canGoForward

chrome.webviewTag.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.

Returns

  • boolean

captureVisibleRegion

chrome.webviewTag.captureVisibleRegion(
  options?: ImageDetails,
  callback: function,
)
Chrome 50+

Captures the visible region of the webview.

Parameters

  • options

    ImageDetails optional

  • callback

    function

    The callback parameter looks like: (dataUrl: string) => void

    • dataUrl

      string

      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

chrome.webviewTag.clearData(
  options: ClearDataOptions,
  types: ClearDataTypeSet,
  callback?: function,
)

Clears browsing data for the webview partition.

Parameters

  • Options determining which data to clear.

  • The types of data to be cleared.

  • callback

    function optional

    The callback parameter looks like: () => void

executeScript

chrome.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 of the script to run.

  • callback

    function optional

    The callback parameter looks like: (result?: any[]) => void

    • result

      any[] optional

      The result of the script in every injected frame.

find

chrome.webviewTag.find(
  searchText: string,
  options?: FindOptions,
  callback?: function,
)

Initiates a find-in-page request.

Parameters

  • searchText

    string

    The string to find in the page.

  • options

    FindOptions optional

    Options for the find request.

  • callback

    function optional

    The callback parameter looks like: (results?: FindCallbackResults) => void

    • 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

chrome.webviewTag.forward(
  callback?: function,
)

Navigates forward one history entry if possible. Equivalent to go(1).

Parameters

  • callback

    function optional

    Chrome 44+

    The callback parameter looks like: (success: boolean) => void

    • success

      boolean

      Indicates whether the navigation was successful.

getAudioState

chrome.webviewTag.getAudioState(
  callback: function,
)
Chrome 62+

Queries audio state.

Parameters

  • callback

    function

    The callback parameter looks like: (audible: boolean) => void

    • audible

      boolean

getProcessId

chrome.webviewTag.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.

Returns

  • number

getUserAgent

chrome.webviewTag.getUserAgent()

Returns the user agent string used by the webview for guest page requests.

Returns

  • string

getZoom

chrome.webviewTag.getZoom(
  callback: function,
)

Gets the current zoom factor.

Parameters

  • callback

    function

    The callback parameter looks like: (zoomFactor: number) => void

    • zoomFactor

      number

      The current zoom factor.

getZoomMode

chrome.webviewTag.getZoomMode(
  callback: function,
)
Chrome 43+

Gets the current zoom mode.

Parameters

  • callback

    function

    The callback parameter looks like: (ZoomMode: ZoomMode) => void

    • ZoomMode

      The webview's current zoom mode.

go

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

  • relativeIndex

    number

    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.

  • callback

    function optional

    The callback parameter looks like: (success: boolean) => void

    • success

      boolean

      Indicates whether the navigation was successful.

insertCSS

chrome.webviewTag.insertCSS(
  details: InjectDetails,
  callback?: function,
)

Injects CSS into the guest page.

Parameters

  • Details of the CSS to insert.

  • callback

    function optional

    The callback parameter looks like: () => void

isAudioMuted

chrome.webviewTag.isAudioMuted(
  callback: function,
)
Chrome 62+

Queries whether audio is muted.

Parameters

  • callback

    function

    The callback parameter looks like: (muted: boolean) => void

    • muted

      boolean

isSpatialNavigationEnabled

chrome.webviewTag.isSpatialNavigationEnabled(
  callback: function,
)
Chrome 71+

Queries whether spatial navigation is enabled for the webview.

Parameters

  • callback

    function

    The callback parameter looks like: (enabled: boolean) => void

    • enabled

      boolean

isUserAgentOverridden

chrome.webviewTag.isUserAgentOverridden()

Indicates whether or not the webview's user agent string has been overridden by webviewTag.setUserAgentOverride.

loadDataWithBaseUrl

chrome.webviewTag.loadDataWithBaseUrl(
  dataUrl: string,
  baseUrl: string,
  virtualUrl?: string,
)

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

  • dataUrl

    string

    The data URL to load.

  • baseUrl

    string

    The base URL that will be used for relative links.

  • virtualUrl

    string optional

    The URL that will be displayed to the user (in the address bar).

print

chrome.webviewTag.print()

Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself.

reload

chrome.webviewTag.reload()

Reloads the current top-level page.

removeContentScripts

chrome.webviewTag.removeContentScripts(
  scriptNameList?: string[],
)
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

  • scriptNameList

    string[] optional

    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

chrome.webviewTag.setAudioMuted(
  mute: boolean,
)
Chrome 62+

Sets audio mute state of the webview.

Parameters

  • mute

    boolean

    Mute audio value

setSpatialNavigationEnabled

chrome.webviewTag.setSpatialNavigationEnabled(
  enabled: boolean,
)
Chrome 71+

Sets spatial navigation state of the webview.

Parameters

  • enabled

    boolean

    Spatial navigation state value.

setUserAgentOverride

chrome.webviewTag.setUserAgentOverride(
  userAgent: string,
)

Override the user agent string used by the webview for guest page requests. Overriding will cause the User-Agent Client Hint header values and the values returned by navigator.userAgentData to be empty for guest page requests this override is applied to.

Parameters

  • userAgent

    string

    The user agent string to use.

setZoom

chrome.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 webviewTag.ZoomMode).

Parameters

  • zoomFactor

    number

    The new zoom factor.

  • callback

    function optional

    The callback parameter looks like: () => void

setZoomMode

chrome.webviewTag.setZoomMode(
  ZoomMode: ZoomMode,
  callback?: function,
)
Chrome 43+

Sets the zoom mode of the webview.

Parameters

  • ZoomMode

    Defines how zooming is handled in the webview.

  • callback

    function optional

    The callback parameter looks like: () => void

stop

chrome.webviewTag.stop()

Stops loading the current webview navigation if in progress.

stopFinding

chrome.webviewTag.stopFinding(
  action?: "activate" | "clear" | "keep",
)

Ends the current find session (clearing all highlighting) and cancels all find requests in progress.

Parameters

  • action

    "activate" | "clear" | "keep" optional

    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

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

chrome.webviewTag.close.addListener(
  callback: 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';
});

Parameters

  • callback

    function

    The callback parameter looks like: () => void

consolemessage

chrome.webviewTag.consolemessage.addListener(
  callback: 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);
});

Parameters

  • callback

    function

    The callback parameter looks like: (level: number, message: string, line: number, sourceId: string) => void

    • level

      number

    • message

      string

    • line

      number

    • sourceId

      string

contentload

chrome.webviewTag.contentload.addListener(
  callback: 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"' });
});

Parameters

  • callback

    function

    The callback parameter looks like: () => void

dialog

chrome.webviewTag.dialog.addListener(
  callback: 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.

Parameters

  • callback

    function

    The callback parameter looks like: (messageType: "alert" | "confirm" | "prompt", messageText: string, dialog: DialogController) => void

    • messageType

      "alert" | "confirm" | "prompt"

    • messageText

      string

exit

chrome.webviewTag.exit.addListener(
  callback: 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!';
  }
});

Parameters

  • callback

    function

    The callback parameter looks like: (processID: number, reason: "normal" | "abnormal" | "crash" | "kill") => void

    • processID

      number

    • reason

      "normal" | "abnormal" | "crash" | "kill"

findupdate

chrome.webviewTag.findupdate.addListener(
  callback: 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.

Parameters

  • callback

    function

    The callback parameter looks like: (searchText: string, numberOfMatches: number, activeMatchOrdinal: number, selectionRect: SelectionRect, canceled: boolean, finalUpdate: string) => void

    • searchText

      string

    • numberOfMatches

      number

    • activeMatchOrdinal

      number

    • selectionRect
    • canceled

      boolean

    • finalUpdate

      string

loadabort

chrome.webviewTag.loadabort.addListener(
  callback: 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'.

Parameters

  • callback

    function

    The callback parameter looks like: (url: string, isTopLevel: boolean, code: number, reason: "ERR_ABORTED" | "ERR_INVALID_URL" | "ERR_DISALLOWED_URL_SCHEME" | "ERR_BLOCKED_BY_CLIENT" | "ERR_ADDRESS_UNREACHABLE" | "ERR_EMPTY_RESPONSE" | "ERR_FILE_NOT_FOUND" | "ERR_UNKNOWN_URL_SCHEME") => void

    • url

      string

    • isTopLevel

      boolean

    • code

      number

    • reason

      "ERR_ABORTED" | "ERR_INVALID_URL" | "ERR_DISALLOWED_URL_SCHEME" | "ERR_BLOCKED_BY_CLIENT" | "ERR_ADDRESS_UNREACHABLE" | "ERR_EMPTY_RESPONSE" | "ERR_FILE_NOT_FOUND" | "ERR_UNKNOWN_URL_SCHEME"

loadcommit

chrome.webviewTag.loadcommit.addListener(
  callback: 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.

Parameters

  • callback

    function

    The callback parameter looks like: (url: string, isTopLevel: boolean) => void

    • url

      string

    • isTopLevel

      boolean

loadredirect

chrome.webviewTag.loadredirect.addListener(
  callback: function,
)

Fired when a top-level load request has redirected to a different URL.

Parameters

  • callback

    function

    The callback parameter looks like: (oldUrl: string, newUrl: string, isTopLevel: boolean) => void

    • oldUrl

      string

    • newUrl

      string

    • isTopLevel

      boolean

loadstart

chrome.webviewTag.loadstart.addListener(
  callback: function,
)

Fired when a load has begun.

Parameters

  • callback

    function

    The callback parameter looks like: (url: string, isTopLevel: boolean) => void

    • url

      string

    • isTopLevel

      boolean

loadstop

chrome.webviewTag.loadstop.addListener(
  callback: 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.

Parameters

  • callback

    function

    The callback parameter looks like: () => void

newwindow

chrome.webviewTag.newwindow.addListener(
  callback: 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);
});

Parameters

  • callback

    function

    The callback parameter looks like: (window: NewWindow, targetUrl: string, initialWidth: number, initialHeight: number, name: string, windowOpenDisposition: "ignore" | "save_to_disk" | "current_tab" | "new_background_tab" | "new_foreground_tab" | "new_window" | "new_popup") => void

    • window
    • targetUrl

      string

    • initialWidth

      number

    • initialHeight

      number

    • name

      string

    • windowOpenDisposition

      "ignore" | "save_to_disk" | "current_tab" | "new_background_tab" | "new_foreground_tab" | "new_window" | "new_popup"

permissionrequest

chrome.webviewTag.permissionrequest.addListener(
  callback: 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();
  }
});

Parameters

  • callback

    function

    The callback parameter looks like: (permission: "media" | "geolocation" | "pointerLock" | "download" | "loadplugin" | "filesystem" | "fullscreen", request: object) => void

    • permission

      "media" | "geolocation" | "pointerLock" | "download" | "loadplugin" | "filesystem" | "fullscreen"

    • request

      object

responsive

chrome.webviewTag.responsive.addListener(
  callback: 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';
});

Parameters

  • callback

    function

    The callback parameter looks like: (processID: number) => void

    • processID

      number

sizechanged

chrome.webviewTag.sizechanged.addListener(
  callback: function,
)

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

Parameters

  • callback

    function

    The callback parameter looks like: (oldWidth: number, oldHeight: number, newWidth: number, newHeight: number) => void

    • oldWidth

      number

    • oldHeight

      number

    • newWidth

      number

    • newHeight

      number

unresponsive

chrome.webviewTag.unresponsive.addListener(
  callback: 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.

Parameters

  • callback

    function

    The callback parameter looks like: (processID: number) => void

    • processID

      number

zoomchange

chrome.webviewTag.zoomchange.addListener(
  callback: function,
)

Fired when the page's zoom changes.

Parameters

  • callback

    function

    The callback parameter looks like: (oldZoomFactor: number, newZoomFactor: number) => void

    • oldZoomFactor

      number

    • newZoomFactor

      number

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.