WebViewCompat
class WebViewCompat
Compatibility version of WebView
Summary
Nested types |
|---|
@Retention(value = RetentionPolicy.CLASS)Denotes that the async startup-related API (e.g |
@Retention(value = RetentionPolicy.CLASS)Denotes that the Navigate API surface is experimental. |
interface WebViewCompat.VisualStateCallbackCallback interface supplied to |
interface WebViewCompat.WebMessageListenerThis listener receives messages sent on the JavaScript object which was injected by |
|
This interface is deprecated. This is set for removal in the next release, use |
Constants |
|
|---|---|
const Int |
Injection event for when all primary resources have been loaded. |
const Int |
Injection event for when Document is first created, before the rest of the page loads. |
Public functions |
|
|---|---|
java-static ScriptHandler |
@UiThreadAdds a JavaScript script to the |
java-static ScriptHandler |
@UiThreadAdds a JavaScript script to the |
java-static Unit |
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Adds a |
java-static Unit |
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Adds a |
java-static Unit |
@UiThreadAdds a |
java-static Unit |
@UiThreadAdds a WebMessageListener to the |
java-static Array<WebMessagePortCompat!> |
@UiThreadCreates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. |
java-static PackageInfo? |
@AnyThreadIf WebView has already been loaded into the current process this method will return the package that was used to load it. |
java-static JavaScriptExecutionWorld |
@UiThreadReturns a JavaScriptExecutionWorld for the given name. |
java-static Profile |
@UiThreadGets the Profile associated with this WebView. |
java-static Uri |
@AnyThreadReturns a URL pointing to the privacy policy for Safe Browsing reporting. |
java-static String |
@AnyThreadGets the WebView variations encoded to be used as the X-Client-Data HTTP header. |
java-static WebChromeClient? |
@UiThreadGets the WebChromeClient. |
java-static WebViewClient |
@UiThreadGets the WebViewClient for the WebView argument. |
java-static WebViewRenderProcess? |
@UiThreadGets the WebView renderer associated with this WebView. |
java-static WebViewRenderProcessClient? |
@UiThreadGets the renderer client object associated with this WebView. |
java-static Boolean |
@UiThreadReturns whether this WebView is muted. |
java-static Boolean |
@AnyThreadReturns true if |
java-static Navigation |
@RequiresFeature(name = WebViewFeature.WEBVIEW_NAVIGATE_EXPERIMENTAL_V1, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Navigates the provided WebView to the given url, with configuration provided by |
java-static Unit |
@UiThreadPosts a |
java-static Unit |
@UiThreadPost a message to main frame. |
java-static Unit |
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Starts a URL prerender request for this WebView. |
java-static Unit |
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")The same as |
java-static Unit |
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")This function is deprecated. use |
java-static Unit |
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Removes a |
java-static Unit |
@UiThreadRemoves the |
java-static Unit |
@UiThreadRemoves a WebMessageListener from the |
java-static Unit |
@RequiresFeature(name = WebViewFeature.SAVE_STATE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")Saves the state of the provided WebView, such as for use with onSaveInstanceState. |
java-static Unit |
@UiThreadMute or un-mute this WebView. |
java-static Unit |
@AnyThreadSets the default |
java-static Unit |
@UiThreadSets the Profile with its name as the current Profile for this WebView. |
java-static Unit |
@AnyThreadConfigures a set of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. |
java-static Unit |
@AnyThreadThis function is deprecated. Please use |
java-static Unit |
@UiThreadSets the renderer client object associated with this WebView. |
java-static Unit |
@UiThreadSets the renderer client object associated with this WebView. |
java-static Unit |
@AnyThreadThis function is deprecated. In WebView version 122.0.6174.0 and later, this initialization is done automatically, so there is no need to call this API. |
java-static Unit |
@WebViewCompat.ExperimentalAsyncStartUpThis function is deprecated. This is an experimental version and is planned to be removed in the next release. |
java-static Unit |
@AnyThreadAsynchronously trigger WebView startup. |
Constants
INJECTION_EVENT_DOCUMENT_END
const val INJECTION_EVENT_DOCUMENT_END = 1: Int
Injection event for when all primary resources have been loaded. Corresponds to DomContentLoaded. See addJavaScriptOnEvent for usage.
INJECTION_EVENT_DOCUMENT_START
const val INJECTION_EVENT_DOCUMENT_START = 0: Int
Injection event for when Document is first created, before the rest of the page loads. See addJavaScriptOnEvent for usage.
Public functions
addDocumentStartJavaScript
@UiThread
@RequiresFeature(name = WebViewFeature.DOCUMENT_START_SCRIPT, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun addDocumentStartJavaScript(
webview: WebView,
script: String,
allowedOriginRules: (Mutable)Set<String!>
): ScriptHandler
Adds a JavaScript script to the WebView which will be executed in any frame whose origin matches allowedOriginRules when the document begins to load.
Note that the script will run before any of the page's JavaScript code and the DOM tree might not be ready at this moment. It will block the loading of the page until it's finished, so should be kept as short as possible.
The injected object from addWebMessageListener API will be injected first and the script can rely on the injected object to send messages to the app.
The script will only run in frames which begin loading after the call returns, therefore it should typically be called before making any loadUrl(), loadData() or loadDataWithBaseURL() call to load the page.
This method can be called multiple times to inject multiple scripts. If more than one script matches a frame's origin, they will be executed in the order they were added.
See addWebMessageListener for the rules of the allowedOriginRules parameter.
This method should only be called if isFeatureSupported returns true for DOCUMENT_START_SCRIPT.
| Parameters | |
|---|---|
webview: WebView |
The |
script: String |
The JavaScript script to be executed. |
allowedOriginRules: (Mutable)Set<String!> |
A set of matching rules for the allowed origins. |
| Returns | |
|---|---|
ScriptHandler |
the |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If one of the |
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
addWebMessageListener |
|
ScriptHandler |
addJavaScriptOnEvent
@UiThread
@RequiresFeature(name = WebViewFeature.JS_INJECTION_IN_FRAME_AND_WORLD, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun addJavaScriptOnEvent(
webview: WebView,
script: String,
injectionEvent: Int,
allowedOriginRules: (Mutable)Set<String!>,
world: JavaScriptExecutionWorld
): ScriptHandler
Adds a JavaScript script to the WebView which will be executed in any frame whose origin matches allowedOriginRules at the page lifecycle event specified in the execution world specified.
An object injected through the addWebMessageListener API will be injected first and the script can rely on the injected object to send messages to the app. The script will only be able to call message listeners registered in the same execution world.
The script will only run in frames which begin loading after the call returns, therefore it should typically be called before making any loadUrl(), loadData() or loadDataWithBaseURL() call to load the page.
This method can be called multiple times to inject multiple scripts. If more than one script matches a frame's origin, they will be executed in the order they were added.
See addWebMessageListener for the rules of the allowedOriginRules parameter.
This method should only be called if isFeatureSupported returns true for JS_INJECTION_IN_FRAME_AND_WORLD.
| Parameters | |
|---|---|
webview: WebView |
The |
script: String |
The JavaScript script to be executed. |
injectionEvent: Int |
The lifecycle event to inject the script: either |
allowedOriginRules: (Mutable)Set<String!> |
A set of matching rules for the allowed origins. |
world: JavaScriptExecutionWorld |
The execution world to inject the script. |
| Returns | |
|---|---|
ScriptHandler |
the |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If one of the |
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
addWebMessageListener |
|
ScriptHandler |
addNavigationListener
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
java-static fun addNavigationListener(webView: WebView, listener: NavigationListener): Unit
Adds a NavigationListener to the given WebView.
A listener can only be added to a WebView once. Attempting to add the same listener to the same WebView twice will result in an IllegalStateException.
The callback will be executed on the main thread using getMainLooper. To specify the execution thread, use addNavigationListener.
| Parameters | |
|---|---|
webView: WebView |
The |
listener: NavigationListener |
The |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
addNavigationListener |
addNavigationListener
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
java-static fun addNavigationListener(
webView: WebView,
executor: Executor,
listener: NavigationListener
): Unit
Adds a NavigationListener to the given WebView.
A listener can only be added to a WebView once. Attempting to add the same listener to the same WebView twice will result in an IllegalStateException.
| Parameters | |
|---|---|
webView: WebView |
The |
executor: Executor |
|
listener: NavigationListener |
The |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the |
java.lang.UnsupportedOperationException |
if the |
addWebMessageListener
@UiThread
@RequiresFeature(name = WebViewFeature.WEB_MESSAGE_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun addWebMessageListener(
webView: WebView,
jsObjectName: String,
allowedOriginRules: (Mutable)Set<String!>,
listener: WebViewCompat.WebMessageListener
): Unit
Adds a WebMessageListener to the WebView and injects a JavaScript object into each frame that the WebMessageListener will listen on.
The injected JavaScript object will be named jsObjectName in the global scope. This will inject the JavaScript object in any frame whose origin matches
allowedOriginRules for every navigation after this call, and the JavaScript object will be available immediately when the page begins to load.
Each allowedOriginRules entry must follow the format SCHEME "://" [
HOSTNAME_PATTERN [ ":" PORT ] ], each part is explained in the below table:
| Rule | Description | Example |
|---|---|---|
| http/https with hostname | SCHEME is http or https; HOSTNAME_PATTERN is a regular hostname;
PORT is optional, when not present, the rule will match port 80 for http and port 443 for https. |
|
| http/https with pattern matching | SCHEME is http or https; HOSTNAME_PATTERN is a sub-domain matching pattern with a leading *.; PORT is optional, when not present, the rule will match port 80 for http and port 443 for https. |
|
| http/https with IP literal | SCHEME is https or https; HOSTNAME_PATTERN is IP literal; PORT is optional, when not present, the rule will match port 80 for http and port 443 for https. |
|
| Custom scheme | SCHEME is a custom scheme; HOSTNAME_PATTERN and PORT must not be present. |
|
* |
Wildcard rule, matches any origin. |
|
Note that this is a powerful API, as the JavaScript object will be injected when the frame's origin matches any one of the allowed origins. The HTTPS scheme is strongly recommended for security; allowing HTTP origins exposes the injected object to any potential network-based attackers. If a wildcard "*" is provided, it will inject the JavaScript object to all frames. A wildcard should only be used if the app wants any third party web page to be able to use the injected object. When using a wildcard, the app must treat received messages as untrustworthy and validate any data carefully.
This method can be called multiple times to inject multiple JavaScript objects.
Let's say the injected JavaScript object is named myObject. We will have following methods on that object once it is available to use:
// Web page (in JavaScript) // message needs to be a JavaScript String or ArrayBuffer, MessagePorts is an optional // parameter. myObject.postMessage(message[, MessagePorts])// To receive messages posted from the app side, assign a function to the "onmessage" // property. This function should accept a single "event" argument. "event" has a "data" // property, which is the message String or ArrayBuffer from the app side. myObject.onmessage = function(event) { ... }
// To be compatible with DOM EventTarget's addEventListener, it accepts type and listener // parameters, where type can be only "message" type and listener can only be a JavaScript // function for myObject. An event object will be passed to listener with a "data" property, // which is the message String or ArrayBuffer from the app side. myObject.addEventListener(type, listener)
// To be compatible with DOM EventTarget's removeEventListener, it accepts type and listener // parameters, where type can be only "message" type and listener can only be a JavaScript // function for myObject. myObject.removeEventListener(type, listener)
We start the communication between JavaScript and the app from the JavaScript side. In order to send message from the app to JavaScript, it needs to post a message from JavaScript first, so the app will have a JavaScriptReplyProxy object to respond. Example:
// Web page (in JavaScript) myObject.onmessage = function(event) { // prints "Got it!" when we receive the app's response. console.log(event.data); } myObject.postMessage("I'm ready!");
// App (in Java) WebMessageListener myListener = new WebMessageListener() { @Override public void onPostMessage(WebView view, WebMessageCompat message, Uri sourceOrigin, boolean isMainFrame, JavaScriptReplyProxy replyProxy) { // do something about view, message, sourceOrigin and isMainFrame. replyProxy.postMessage("Got it!"); } }; if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { WebViewCompat.addWebMessageListener(webView, "myObject", rules, myListener); }
Suppose the communication is already setup, to send ArrayBuffer from the app to web, it needs to check feature flag(WEB_MESSAGE_ARRAY_BUFFER). Here is a example to send file content from app to web:
// App (in Java) WebMessageListener myListener = new WebMessageListener() { @Override public void onPostMessage(WebView view, WebMessageCompat message, Uri sourceOrigin, boolean isMainFrame, JavaScriptReplyProxy replyProxy) { // Communication is setup, send file data to web. if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_ARRAY_BUFFER)) { // Suppose readFileData method is to read content from file. byte[] fileData = readFileData("myFile.dat"); replyProxy.postMessage(fileData); } } }
// Web page (in JavaScript) myObject.onmessage = function(event) { if (event.data instanceof ArrayBuffer) { const data = event.data; // Received file content from app. const dataView = new DataView(data); // Consume file content by using JavaScript DataView to access ArrayBuffer. } } myObject.postMessage("Setup!");
Suppose the communication is already setup, and feature flag WEB_MESSAGE_ARRAY_BUFFER is check. Here is a example to download image in WebView, and send to app:
// Web page (in JavaScript) const response = await fetch('example.jpg'); if (response.ok) { const imageData = await response.arrayBuffer(); myObject.postMessage(imageData); }
// App (in Java) WebMessageListener myListener = new WebMessageListener() { @Override public void onPostMessage(WebView view, WebMessageCompat message, Uri sourceOrigin, boolean isMainFrame, JavaScriptReplyProxy replyProxy) { if (message.getType() == WebMessageCompat.TYPE_ARRAY_BUFFER) { byte[] imageData = message.getArrayBuffer(); // do something like draw image on ImageView. } } };
| Parameters | |
|---|---|
webView: WebView |
The |
jsObjectName: String |
The name for the injected JavaScript object for this |
allowedOriginRules: (Mutable)Set<String!> |
A set of matching rules for the allowed origins. |
listener: WebViewCompat.WebMessageListener |
The |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If one of the |
java.lang.UnsupportedOperationException |
if the |
addWebMessageListener
@UiThread
@RequiresFeature(name = WebViewFeature.JS_INJECTION_IN_FRAME_AND_WORLD, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun addWebMessageListener(
webView: WebView,
jsObjectName: String,
allowedOriginRules: (Mutable)Set<String!>,
world: JavaScriptExecutionWorld,
listener: WebViewCompat.WebMessageListener
): Unit
Adds a WebMessageListener to the WebView which will receive messages posted from the specified JavaScriptExecutionWorld.
Note that WebMessageListeners added through this API are keyed on both name and world. jsObjectName only need to be unique per world. That is, it is possible to add the same jsObjectName to 2 or more worlds.
This method should only be called if isFeatureSupported returns true for JS_INJECTION_IN_FRAME_AND_WORLD.
| Parameters | |
|---|---|
webView: WebView |
The |
jsObjectName: String |
The name of the JavaScript object to be injected. |
allowedOriginRules: (Mutable)Set<String!> |
A set of matching rules for the allowed origins. |
world: JavaScriptExecutionWorld |
The |
listener: WebViewCompat.WebMessageListener |
The listener to receive messages. |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If the |
java.lang.UnsupportedOperationException |
if the |
createWebMessageChannel
@UiThread
@RequiresFeature(name = WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun createWebMessageChannel(webview: WebView): Array<WebMessagePortCompat!>
Creates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. The HTML5 message channel functionality is described here
The returned message channels are entangled and already in started state.
| Returns | |
|---|---|
Array<WebMessagePortCompat!> |
an array of size two, containing the two message ports that form the message channel. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getCurrentWebViewPackage
@AnyThread
java-static fun getCurrentWebViewPackage(context: Context): PackageInfo?
If WebView has already been loaded into the current process this method will return the package that was used to load it. Otherwise, the package that would be used if the WebView was loaded right now will be returned; this does not cause WebView to be loaded, so this information may become outdated at any time. The WebView package changes either when the current WebView package is updated, disabled, or uninstalled. It can also be changed through a Developer Setting. If the WebView package changes, any app process that has loaded WebView will be killed. The next time the app starts and loads WebView it will use the new WebView package instead.
| Returns | |
|---|---|
PackageInfo? |
the current WebView package, or |
getExecutionWorld
@UiThread
@RequiresFeature(name = WebViewFeature.JS_INJECTION_IN_FRAME_AND_WORLD, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getExecutionWorld(webview: WebView, name: String): JavaScriptExecutionWorld
Returns a JavaScriptExecutionWorld for the given name.
Use PAGE_WORLD_NAME to get the default execution world. Worlds are associated with the WebView they are created for. Using a world from one WebView with another WebView will throw an exception.
This method should only be called if isFeatureSupported returns true for JS_INJECTION_IN_FRAME_AND_WORLD.
| Parameters | |
|---|---|
webview: WebView |
The WebView object to associate with the world. |
name: String |
The name of the execution world. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getProfile
@UiThread
@RequiresFeature(name = WebViewFeature.MULTI_PROFILE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getProfile(webView: WebView): Profile
Gets the Profile associated with this WebView.
Gets the profile object set on this WebView using setProfile, or the default profile if it has not been changed.
| Parameters | |
|---|---|
webView: WebView |
the WebView to get the profile object associated with. |
| Returns | |
|---|---|
Profile |
the profile object set to this WebView. |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the WebView has been destroyed. |
java.lang.UnsupportedOperationException |
if the |
getSafeBrowsingPrivacyPolicyUrl
@AnyThread
@RequiresFeature(name = WebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getSafeBrowsingPrivacyPolicyUrl(): Uri
Returns a URL pointing to the privacy policy for Safe Browsing reporting.
| Returns | |
|---|---|
Uri |
the url pointing to a privacy policy document which can be displayed to users. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getVariationsHeader
@AnyThread
@RequiresFeature(name = WebViewFeature.GET_VARIATIONS_HEADER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getVariationsHeader(): String
Gets the WebView variations encoded to be used as the X-Client-Data HTTP header.
The app is responsible for adding the X-Client-Data header to any request that may use variations metadata, such as requests to Google web properties. The returned string will be a base64 encoded ClientVariations proto: https://source.chromium.org/chromium/chromium/src/+/main:components/variations/proto/client_variations.proto
| Returns | |
|---|---|
String |
the variations header. The string may be empty if the header is not available. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
loadUrl |
getWebChromeClient
@UiThread
@RequiresFeature(name = WebViewFeature.GET_WEB_CHROME_CLIENT, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getWebChromeClient(webview: WebView): WebChromeClient?
Gets the WebChromeClient.
| Returns | |
|---|---|
WebChromeClient? |
the WebChromeClient, or |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getWebViewClient
@UiThread
@RequiresFeature(name = WebViewFeature.GET_WEB_VIEW_CLIENT, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getWebViewClient(webview: WebView): WebViewClient
Gets the WebViewClient for the WebView argument.
| Returns | |
|---|---|
WebViewClient |
the WebViewClient, or a default client if not yet set |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getWebViewRenderProcess
@UiThread
@RequiresFeature(name = WebViewFeature.GET_WEB_VIEW_RENDERER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getWebViewRenderProcess(webview: WebView): WebViewRenderProcess?
Gets the WebView renderer associated with this WebView.
In Android O and above, WebView may run in "multiprocess" mode. In multiprocess mode, rendering of web content is performed by a sandboxed renderer process separate to the application process. This renderer process may be shared with other WebViews in the application, but is not shared with other application processes.
If WebView is running in multiprocess mode, this method returns a handle to the renderer process associated with the WebView, which can be used to control the renderer process.
| Returns | |
|---|---|
WebViewRenderProcess? |
the |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
getWebViewRenderProcessClient
@UiThread
@RequiresFeature(name = WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun getWebViewRenderProcessClient(webview: WebView): WebViewRenderProcessClient?
Gets the renderer client object associated with this WebView.
| Returns | |
|---|---|
WebViewRenderProcessClient? |
the |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
isAudioMuted
@UiThread
@RequiresFeature(name = WebViewFeature.MUTE_AUDIO, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun isAudioMuted(webView: WebView): Boolean
Returns whether this WebView is muted.
| Parameters | |
|---|---|
webView: WebView |
the WebView for which to check mute status. |
| Returns | |
|---|---|
Boolean |
true if the WebView is muted, false otherwise. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
isMultiProcessEnabled
@AnyThread
@RequiresFeature(name = WebViewFeature.MULTI_PROCESS, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun isMultiProcessEnabled(): Boolean
Returns true if WebView is running in multi process mode.
In Android O and above, WebView may run in "multiprocess" mode. In multiprocess mode, rendering of web content is performed by a sandboxed renderer process separate to the application process. This renderer process may be shared with other WebViews in the application, but is not shared with other application processes.
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
navigate
@RequiresFeature(name = WebViewFeature.WEBVIEW_NAVIGATE_EXPERIMENTAL_V1, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@WebViewCompat.ExperimentalNavigate
java-static fun navigate(webview: WebView, url: String, params: NavigationParameters): Navigation
Navigates the provided WebView to the given url, with configuration provided by NavigationParameters.
Note that this method is more flexible than loadUrl, with more features available on the builder and different header handling, (see addAdditionalHeader).
| Parameters | |
|---|---|
webview: WebView |
The WebView to perform the navigation on. |
url: String |
The URL to load. |
params: NavigationParameters |
The navigation parameters. |
| Returns | |
|---|---|
Navigation |
Navigation object that can be used to track progress through NavigationListener callbacks. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
postVisualStateCallback
@UiThread
@RequiresFeature(name = WebViewFeature.VISUAL_STATE_CALLBACK, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun postVisualStateCallback(
webview: WebView,
requestId: Long,
callback: WebViewCompat.VisualStateCallback
): Unit
Posts a VisualStateCallback, which will be called when the current state of the WebView is ready to be drawn.
Because updates to the DOM are processed asynchronously, updates to the DOM may not immediately be reflected visually by subsequent onDraw invocations. The VisualStateCallback provides a mechanism to notify the caller when the contents of the DOM at the current time are ready to be drawn the next time the WebView draws.
The next draw after the callback completes is guaranteed to reflect all the updates to the DOM up to the point at which the VisualStateCallback was posted, but it may also contain updates applied after the callback was posted.
The state of the DOM covered by this API includes the following:
- primitive HTML elements (div, img, span, etc..)
- images
- CSS animations
- WebGL
- canvas
- the video tag
To guarantee that the WebView will successfully render the first frame after the onComplete method has been called a set of conditions must be met:
- If the
WebView's visibility is set toVISIBLEthen * theWebViewmust be attached to the view hierarchy. - If the
WebView's visibility is set toINVISIBLEthen theWebViewmust be attached to the view hierarchy and must be madeVISIBLEfrom theonCompletemethod. - If the
WebView's visibility is set toGONEthen theWebViewmust be attached to the view hierarchy and itsLayoutParams's width and height need to be set to fixed values and must be madeVISIBLEfrom theonCompletemethod.
When using this API it is also recommended to enable pre-rasterization if the WebView is off screen to avoid flickering. See setOffscreenPreRaster for more details and do consider its caveats.
| Parameters | |
|---|---|
webview: WebView |
The WebView to post to. |
requestId: Long |
An id that will be returned in the callback to allow callers to match requests with callbacks. |
callback: WebViewCompat.VisualStateCallback |
The callback to be invoked. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
postWebMessage
@UiThread
@RequiresFeature(name = WebViewFeature.POST_WEB_MESSAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun postWebMessage(
webview: WebView,
message: WebMessageCompat,
targetOrigin: Uri
): Unit
Post a message to main frame. The embedded application can restrict the messages to a certain target origin. See HTML5 spec for how target origin can be used.
A target origin can be set as a wildcard ("*"). However this is not recommended. See the page above for security issues.
When posting a WebMessageCompat with type TYPE_ARRAY_BUFFER, this method should check if isFeatureSupported returns true for WEB_MESSAGE_ARRAY_BUFFER. Example:
if (message.getType() == WebMessageCompat.TYPE_ARRAY_BUFFER) { if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_ARRAY_BUFFER) { // ArrayBuffer message is supported, send message here. WebViewCompat.postWebMessage(webview, message, ...); } }
| Parameters | |
|---|---|
webview: WebView |
The WebView to post to. |
message: WebMessageCompat |
the WebMessage |
targetOrigin: Uri |
the target origin. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
prerenderUrlAsync
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
java-static fun prerenderUrlAsync(
webView: WebView,
url: String,
cancellationSignal: CancellationSignal?,
callbackExecutor: Executor,
callback: PrerenderOperationCallback
): Unit
Starts a URL prerender request for this WebView. Must be called from the UI thread.
This WebView will match a prerender request to a navigation, such as a call to loadUrl or a click on a hyperlink. The matching behavior is as follows:
- By default, if the server does not provide a
No-Vary-SearchHTTP header, an exact URL match is required. - If the server provides a
No-Vary-SearchHTTP header, matching will be performed according to the rules specified by the header. See the prerender documentation for more details.
PrerenderParameters.
If a prerender request is matched, WebView will use the prerendered page. This includes requests that are still in progress. If no match is found, the URL will be handled normally (i.e., through a new network request).
Applications will still be responsible for calling loadUrl to display web contents in a WebView.
A prerendered page can also match a navigation initiated by clicking a hyperlink.
Only supports HTTPS scheme.
The CancellationSignal will make the best effort to cancel an in-flight prerender request; however cancellation it is not guaranteed.
| Parameters | |
|---|---|
webView: WebView |
the WebView for which we trigger the prerender request. |
url: String |
the url associated with the prerender request. |
cancellationSignal: CancellationSignal? |
used to trigger prerender cancellation. |
callbackExecutor: Executor |
the executor to resolve the callback with. |
callback: PrerenderOperationCallback |
callbacks for reporting result back to application. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
prerenderUrlAsync
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
@Profile.ExperimentalUrlPrefetch
java-static fun prerenderUrlAsync(
webView: WebView,
url: String,
cancellationSignal: CancellationSignal?,
callbackExecutor: Executor,
params: PrerenderParameters,
callback: PrerenderOperationCallback
): Unit
The same as prerenderUrlAsync, but allows customizing the request by providing PrerenderParameters.
When PrerenderParameters are provided, they determine the URL matching behavior, taking precedence over the default behavior or any No-Vary-Search header sent by the server. See PrerenderParameters for more details on how to configure the matching algorithm.
| Parameters | |
|---|---|
webView: WebView |
the WebView for which we trigger the prerender request. |
url: String |
the url associated with the prerender request. |
cancellationSignal: CancellationSignal? |
used to trigger prerender cancellation. |
callbackExecutor: Executor |
the executor to resolve the callback with. |
params: PrerenderParameters |
parameters to customize the prerender request and its matching behavior. |
callback: PrerenderOperationCallback |
callbacks for reporting result back to application. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
prerenderUrlAsync
@RequiresFeature(name = WebViewFeature.PRERENDER_WITH_URL, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
@Profile.ExperimentalUrlPrefetch
java-static funprerenderUrlAsync(
webView: WebView,
url: String,
cancellationSignal: CancellationSignal?,
callbackExecutor: Executor,
params: SpeculativeLoadingParameters,
callback: PrerenderOperationCallback
): Unit
The same as prerenderUrlAsync, but allows customizing the request by providing SpeculativeLoadingParameters.
When SpeculativeLoadingParameters are provided, they determine the URL matching behavior, taking precedence over the default behavior or any No-Vary-Search header sent by the server. See SpeculativeLoadingParameters for more details on how to configure the matching algorithm.
| Parameters | |
|---|---|
webView: WebView |
the WebView for which we trigger the prerender request. |
url: String |
the url associated with the prerender request. |
cancellationSignal: CancellationSignal? |
used to trigger prerender cancellation. |
callbackExecutor: Executor |
the executor to resolve the callback with. |
params: SpeculativeLoadingParameters |
parameters to customize the prerender request and its matching behavior. |
callback: PrerenderOperationCallback |
callbacks for reporting result back to application. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
removeNavigationListener
@RequiresFeature(name = WebViewFeature.NAVIGATION_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
java-static fun removeNavigationListener(webView: WebView, listener: NavigationListener): Unit
Removes a NavigationListener from the given WebView.
This method does nothing, if the listener has not previously been added with addNavigationListener.
| Parameters | |
|---|---|
webView: WebView |
The |
listener: NavigationListener |
The |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
addNavigationListener |
removeWebMessageListener
@UiThread
@RequiresFeature(name = WebViewFeature.WEB_MESSAGE_LISTENER, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun removeWebMessageListener(webview: WebView, jsObjectName: String): Unit
Removes the WebMessageListener associated with
jsObjectName.
Note that after this call, the injected JavaScript object is still in the JavaScript context, however any message sent after this call won't reach the WebMessageListener.
| Parameters | |
|---|---|
webview: WebView |
The WebView object to remove from. |
jsObjectName: String |
The JavaScript object's name that was previously passed to |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
| See also | |
|---|---|
addWebMessageListener |
removeWebMessageListener
@UiThread
@RequiresFeature(name = WebViewFeature.JS_INJECTION_IN_FRAME_AND_WORLD, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun removeWebMessageListener(
webview: WebView,
world: JavaScriptExecutionWorld,
jsObjectName: String
): Unit
Removes a WebMessageListener from the WebView in the specified execution world.
If there are 2 listeners with the same name but in different worlds, this will only remove the web listener from the world specified. If there is no listener with jsObjectName in the world, this will be a no-op.
This method should only be called if isFeatureSupported returns true for JS_INJECTION_IN_FRAME_AND_WORLD.
| Parameters | |
|---|---|
webview: WebView |
The |
world: JavaScriptExecutionWorld |
The execution world from which to remove the listener. |
jsObjectName: String |
The name of the JavaScript object that was previously added. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
saveState
@RequiresFeature(name = WebViewFeature.SAVE_STATE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
@UiThread
java-static fun saveState(
webView: WebView,
outState: Bundle,
maxSizeBytes: @IntRange(from = 1) Int,
includeForwardState: Boolean
): Unit
Saves the state of the provided WebView, such as for use with onSaveInstanceState. This is an extension of saveState and the returned state can be restored through restoreState.
| Parameters | |
|---|---|
webView: WebView |
the |
outState: Bundle |
the |
maxSizeBytes: @IntRange(from = 1) Int |
the maximum size (in bytes) that the returned state can be. If the WebView contains more state, history entries further back will not be saved. |
includeForwardState: Boolean |
whether to include entries that can only be reached through going forward in history (such as through |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
setAudioMuted
@UiThread
@RequiresFeature(name = WebViewFeature.MUTE_AUDIO, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setAudioMuted(webView: WebView, mute: Boolean): Unit
Mute or un-mute this WebView.
| Parameters | |
|---|---|
webView: WebView |
the WebView for which to control muting. |
mute: Boolean |
true to mute the WebView; false to un-mute the WebView. |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
setDefaultTrafficStatsTag
@AnyThread
@RequiresFeature(name = WebViewFeature.DEFAULT_TRAFFICSTATS_TAGGING, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setDefaultTrafficStatsTag(tag: Int): Unit
Sets the default TrafficStats tag to use when accounting socket traffic caused by WebView. If set, this tag is global for all requests sent by the WebView library within your app.
If no tag is set (e.g. this method isn't called), then Android accounts for the socket traffic caused by WebView as if the tag value were set to 0. See setThreadStatsTag for more information.
NOTE: Setting a tag disallows sharing of sockets with requests with other tags, which may adversely affect performance by prohibiting connection sharing. In other words, use of multiplexed sockets (e.g. HTTP/2 and QUIC) will only be allowed if all requests have the same socket tag. To minimize impact, you should not change the value of this tag often.
| Parameters | |
|---|---|
tag: Int |
the tag value used when accounting for socket traffic caused by the WebView library in your app. Tags between |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
setProfile
@UiThread
@RequiresFeature(name = WebViewFeature.MULTI_PROFILE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setProfile(webView: WebView, profileName: String): Unit
Sets the Profile with its name as the current Profile for this WebView.
- This should be called before doing anything else with WebView other than attaching it to the view hierarchy.
- This should be only called if WebView is to use a Profile other than the default.
- This method will create the profile if it doesn't exist.
| Parameters | |
|---|---|
webView: WebView |
the WebView to modify. |
profileName: String |
the name of the profile to use in the passed |
| Throws | |
|---|---|
java.lang.IllegalStateException |
if the WebView has been destroyed. |
java.lang.IllegalStateException |
if the previous profile has been accessed via a call to |
java.lang.IllegalStateException |
if the profile has already been set previously via this method. |
java.lang.IllegalStateException |
if |
java.lang.IllegalStateException |
if the WebView has previously navigated to a web page. |
java.lang.UnsupportedOperationException |
if the |
setSafeBrowsingAllowlist
@AnyThread
@RequiresFeature(name = WebViewFeature.SAFE_BROWSING_ALLOWLIST, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setSafeBrowsingAllowlist(
hosts: (Mutable)Set<String!>,
callback: ValueCallback<Boolean!>?
): Unit
Configures a set of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. The set is global for all the WebViews.
Each rule should take one of these:
| Rule | Example | Matches Subdomain |
|---|---|---|
| HOSTNAME | example.com | Yes |
| .HOSTNAME | .example.com | No |
| IPV4_LITERAL | 192.168.1.1 | No |
| IPV6_LITERAL_WITH_BRACKETS | [10:20:30:40:50:60:70:80] | No |
All other rules, including wildcards, are invalid.
The correct syntax for hosts is defined by RFC 3986.
| Parameters | |
|---|---|
hosts: (Mutable)Set<String!> |
the set of hosts for which to skip Safe Browsing checks |
callback: ValueCallback<Boolean!>? |
will be called with |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
@AnyThread
@ReplaceWith(expression = "setSafeBrowsingAllowlist(new HashSet<>(hosts), callback)", imports = [""java.util.HashSet""])
@RequiresFeature(name = WebViewFeature.SAFE_BROWSING_WHITELIST, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static funsetSafeBrowsingWhitelist(
hosts: (Mutable)List<String!>,
callback: ValueCallback<Boolean!>?
): Unit
Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. The list is global for all the WebViews.
Each rule should take one of these:
| Rule | Example | Matches Subdomain |
|---|---|---|
| HOSTNAME | example.com | Yes |
| .HOSTNAME | .example.com | No |
| IPV4_LITERAL | 192.168.1.1 | No |
| IPV6_LITERAL_WITH_BRACKETS | [10:20:30:40:50:60:70:80] | No |
All other rules, including wildcards, are invalid.
The correct syntax for hosts is defined by RFC 3986.
| Parameters | |
|---|---|
hosts: (Mutable)List<String!> |
the list of hosts |
callback: ValueCallback<Boolean!>? |
will be called with |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
setWebViewRenderProcessClient
@UiThread
@RequiresFeature(name = WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setWebViewRenderProcessClient(
webview: WebView,
webViewRenderProcessClient: WebViewRenderProcessClient?
): Unit
Sets the renderer client object associated with this WebView.
See setWebViewRenderProcessClient for details, with the following differences:
Callbacks will execute directly on the thread on which this WebView was instantiated.
Passing null for webViewRenderProcessClient will clear the renderer client object for this WebView.
This method should only be called if isFeatureSupported returns true for WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE.
| Parameters | |
|---|---|
webview: WebView |
the |
webViewRenderProcessClient: WebViewRenderProcessClient? |
the |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the WebViewFeature#WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE} feature is not supported. |
setWebViewRenderProcessClient
@UiThread
@RequiresFeature(name = WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static fun setWebViewRenderProcessClient(
webview: WebView,
executor: Executor,
webViewRenderProcessClient: WebViewRenderProcessClient
): Unit
Sets the renderer client object associated with this WebView.
The renderer client encapsulates callbacks relevant to WebView renderer state. See WebViewRenderProcessClient for details.
Although many WebView instances may share a single underlying renderer, and renderers may live either in the application process, or in a sandboxed process that is isolated from the application process, instances of WebViewRenderProcessClient are set per-WebView. Callbacks represent renderer events from the perspective of this WebView, and may or may not be correlated with renderer events affecting other WebViews.
| Parameters | |
|---|---|
webview: WebView |
the |
executor: Executor |
the |
webViewRenderProcessClient: WebViewRenderProcessClient |
the |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
@AnyThread
@RequiresFeature(name = WebViewFeature.START_SAFE_BROWSING, enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
java-static funstartSafeBrowsing(context: Context, callback: ValueCallback<Boolean!>?): Unit
Starts Safe Browsing initialization.
URL loads are not guaranteed to be protected by Safe Browsing until after callback is invoked with true. Safe Browsing is not fully supported on all devices. For those devices callback will receive false.
This should not be called if Safe Browsing has been disabled by manifest tag or setSafeBrowsingEnabled. This prepares resources used for Safe Browsing.
This should be called with the Application Context (and will always use the Application context to do its work regardless).
| Parameters | |
|---|---|
context: Context |
Application Context. |
callback: ValueCallback<Boolean!>? |
will be called on the UI thread with |
| Throws | |
|---|---|
java.lang.UnsupportedOperationException |
if the |
@WebViewCompat.ExperimentalAsyncStartUp
@AnyThread
java-static funstartUpWebView(
context: Context,
config: WebViewStartUpConfig,
callback: WebViewCompat.WebViewStartUpCallback
): Unit
Asynchronously trigger WebView startup.
WebView startup is a time-consuming process that is normally triggered during the first usage of WebView related APIs. WebView startup happens once per process. For example, the first call to new WebView() can take longer to complete than future calls due to WebView startup being triggered. The Android UI thread remains blocked till the startup completes.
This method allows callers to trigger WebView startup at a time of their choosing.
There are performance improvements this API provides. This method ensures that the portions of WebView startup which are able to run in the background will do so. Other portions of startup will still run on the UI thread.
Any APIs in android.webkit and androidx.webkit (including WebViewFeature) MUST only be called after the callback is invoked in order to ensure the maximum benefit. There is no feature check or call to WebViewFeature required for using this method.
This API can be called multiple times. The callback will be called promptly if startup has already completed.
This is an experimental API and unsuitable for non-experimental use. This method can be removed in future versions of the library.
| Parameters | |
|---|---|
context: Context |
Application Context. |
config: WebViewStartUpConfig |
configuration for startup. |
callback: WebViewCompat.WebViewStartUpCallback |
the callback triggered when WebView startup is complete. This will be called on the main looper (Looper.getMainLooper()). |
startUpWebView
@AnyThread
java-static fun startUpWebView(
context: Context,
config: WebViewStartUpConfig,
callback: WebViewOutcomeReceiver<WebViewStartUpResult!, WebViewStartupException!>
): Unit
Asynchronously trigger WebView startup.
WebView startup is a time-consuming process that is normally triggered during the first usage of WebView related APIs. WebView startup happens once per process. For example, the first call to new WebView() can take longer to complete than future calls due to WebView startup being triggered. The Android UI thread remains blocked till the startup completes.
This method allows callers to trigger WebView startup at a time of their choosing.
There are performance improvements this API provides. This method ensures that the portions of WebView startup which are able to run in the background will do so. Other portions of startup will still run on the UI thread.
Any APIs in android.webkit and androidx.webkit (including WebViewFeature) MUST only be called after the callback is invoked in order to ensure the maximum benefit. There is no feature check or call to WebViewFeature required for using this method.
This API can be called multiple times. The callback will be called promptly if startup has already completed.
Startup is not expected to fail under normal circumstances, but can in rare cases. If a failure has been reported to the callback, calling any other WebView APIs is likely to throw an exception or immediately crash, and should be avoided if possible.
| Parameters | |
|---|---|
context: Context |
Application Context. |
config: WebViewStartUpConfig |
configuration for startup. |
callback: WebViewOutcomeReceiver<WebViewStartUpResult!, WebViewStartupException!> |
the callback triggered when WebView startup is complete or fails. This will be called on the main looper (Looper.getMainLooper()). |