WebViewCompat
public
class
WebViewCompat
extends Object
java.lang.Object | |
↳ | androidx.webkit.WebViewCompat |
Compatibility version of WebView
Summary
Nested classes | ||
---|---|---|
interface |
WebViewCompat.VisualStateCallback
Callback interface supplied to |
|
interface |
WebViewCompat.WebMessageListener
This listener receives messages sent on the JavaScript object which was injected by |
Public methods | |
---|---|
static
void
|
addWebMessageListener(WebView webView, String jsObjectName, Set<String> allowedOriginRules, WebViewCompat.WebMessageListener listener)
Adds a |
static
WebMessagePortCompat[]
|
createWebMessageChannel(WebView webview)
Creates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. |
static
PackageInfo
|
getCurrentWebViewPackage(Context context)
If WebView has already been loaded into the current process this method will return the package that was used to load it. |
static
Uri
|
getSafeBrowsingPrivacyPolicyUrl()
Returns a URL pointing to the privacy policy for Safe Browsing reporting. |
static
WebChromeClient
|
getWebChromeClient(WebView webview)
Gets the WebChromeClient. |
static
WebViewClient
|
getWebViewClient(WebView webview)
Gets the WebViewClient for the WebView argument. |
static
WebViewRenderProcess
|
getWebViewRenderProcess(WebView webview)
Gets the WebView renderer associated with this WebView. |
static
WebViewRenderProcessClient
|
getWebViewRenderProcessClient(WebView webview)
Gets the renderer client object associated with this WebView. |
static
boolean
|
isMultiProcessEnabled()
Returns true if |
static
void
|
postVisualStateCallback(WebView webview, long requestId, WebViewCompat.VisualStateCallback callback)
Posts a |
static
void
|
postWebMessage(WebView webview, WebMessageCompat message, Uri targetOrigin)
Post a message to main frame. |
static
void
|
removeWebMessageListener(WebView webview, String jsObjectName)
Removes the |
static
void
|
setSafeBrowsingAllowlist(Set<String> hosts, ValueCallback<Boolean> callback)
Configures a set of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. |
static
void
|
setSafeBrowsingWhitelist(List<String> hosts, ValueCallback<Boolean> callback)
This method is deprecated.
Please use |
static
void
|
setWebViewRenderProcessClient(WebView webview, Executor executor, WebViewRenderProcessClient webViewRenderProcessClient)
Sets the renderer client object associated with this WebView. |
static
void
|
setWebViewRenderProcessClient(WebView webview, WebViewRenderProcessClient webViewRenderProcessClient)
Sets the renderer client object associated with this WebView. |
static
void
|
startSafeBrowsing(Context context, ValueCallback<Boolean> callback)
Starts Safe Browsing initialization. |
Inherited methods | |
---|---|
Public methods
addWebMessageListener
public static void addWebMessageListener (WebView webView, String jsObjectName, Set<String> allowedOriginRules, WebViewCompat.WebMessageListener listener)
Adds a WebViewCompat.WebMessageListener
to the WebView
and injects a JavaScript object into
each frame that the WebViewCompat.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, 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 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 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); }
This method should only be called if WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.WEB_MESSAGE_LISTENER
.
Parameters | |
---|---|
webView |
WebView : The WebView instance that we are interacting with. |
jsObjectName |
String : The name for the injected JavaScript object for this WebViewCompat.WebMessageListener . |
allowedOriginRules |
Set : A set of matching rules for the allowed origins. |
listener |
WebViewCompat.WebMessageListener : The WebMessageListener to handle postMessage()
calls on the JavaScript object. |
Throws | |
---|---|
IllegalArgumentException |
If one of the allowedOriginRules is invalid. |
createWebMessageChannel
public static WebMessagePortCompat[] createWebMessageChannel (WebView webview)
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL
.
Parameters | |
---|---|
webview |
WebView |
Returns | |
---|---|
WebMessagePortCompat[] |
an array of size two, containing the two message ports that form the message channel. |
getCurrentWebViewPackage
public static PackageInfo getCurrentWebViewPackage (Context context)
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.
Parameters | |
---|---|
context |
Context |
Returns | |
---|---|
PackageInfo |
the current WebView package, or null if there is none.
|
getSafeBrowsingPrivacyPolicyUrl
public static Uri getSafeBrowsingPrivacyPolicyUrl ()
Returns a URL pointing to the privacy policy for Safe Browsing reporting.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL
.
Returns | |
---|---|
Uri |
the url pointing to a privacy policy document which can be displayed to users. |
getWebChromeClient
public static WebChromeClient getWebChromeClient (WebView webview)
Gets the WebChromeClient.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.GET_WEB_CHROME_CLIENT
.
Parameters | |
---|---|
webview |
WebView |
Returns | |
---|---|
WebChromeClient |
the WebChromeClient, or null if not yet set
|
getWebViewClient
public static WebViewClient getWebViewClient (WebView webview)
Gets the WebViewClient for the WebView argument.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.GET_WEB_VIEW_CLIENT
.
Parameters | |
---|---|
webview |
WebView |
Returns | |
---|---|
WebViewClient |
the WebViewClient, or a default client if not yet set |
getWebViewRenderProcess
public static WebViewRenderProcess getWebViewRenderProcess (WebView webview)
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.GET_WEB_VIEW_RENDERER
.
Parameters | |
---|---|
webview |
WebView |
Returns | |
---|---|
WebViewRenderProcess |
the WebViewRenderProcess renderer handle associated
with this WebView , or null if
WebView is not runing in multiprocess mode.
|
getWebViewRenderProcessClient
public static WebViewRenderProcessClient getWebViewRenderProcessClient (WebView webview)
Gets the renderer client object associated with this WebView.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE
.
Parameters | |
---|---|
webview |
WebView |
Returns | |
---|---|
WebViewRenderProcessClient |
the WebViewRenderProcessClient object associated with this WebView, if
one has been set via
setWebViewRenderProcessClient(WebView, WebViewRenderProcessClient) or null
otherwise.
|
isMultiProcessEnabled
public static boolean isMultiProcessEnabled ()
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.
Returns | |
---|---|
boolean |
postVisualStateCallback
public static void postVisualStateCallback (WebView webview, long requestId, WebViewCompat.VisualStateCallback callback)
Posts a WebViewCompat.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 WebView.onDraw(Canvas)
invocations. The
WebViewCompat.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 WebViewCompat.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 WebViewCompat.VisualStateCallback.onComplete(long)
method has been called a set of
conditions must be met:
- If the
WebView
's visibility is set toVISIBLE
then * theWebView
must be attached to the view hierarchy. - If the
WebView
's visibility is set toINVISIBLE
then theWebView
must be attached to the view hierarchy and must be madeVISIBLE
from theWebViewCompat.VisualStateCallback.onComplete(long)
method. - If the
WebView
's visibility is set toGONE
then theWebView
must be attached to the view hierarchy and itsLayoutParams
's width and height need to be set to fixed values and must be madeVISIBLE
from theWebViewCompat.VisualStateCallback.onComplete(long)
method.
When using this API it is also recommended to enable pre-rasterization if the WebView
is off screen to avoid flickering. See
WebSettings.setOffscreenPreRaster(boolean)
for more details and do consider its
caveats.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.VISUAL_STATE_CALLBACK
.
Parameters | |
---|---|
webview |
WebView |
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.
|
postWebMessage
public static void postWebMessage (WebView webview, WebMessageCompat message, Uri targetOrigin)
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.POST_WEB_MESSAGE
.
Parameters | |
---|---|
webview |
WebView |
message |
WebMessageCompat : the WebMessage |
targetOrigin |
Uri : the target origin.
|
removeWebMessageListener
public static void removeWebMessageListener (WebView webview, String jsObjectName)
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
.
This method should only be called if WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.WEB_MESSAGE_LISTENER
.
Parameters | |
---|---|
webview |
WebView |
jsObjectName |
String : The JavaScript object's name that was previously passed to addWebMessageListener(WebView, String, Set, WebMessageListener) . |
setSafeBrowsingAllowlist
public static void setSafeBrowsingAllowlist (Set<String> hosts, ValueCallback<Boolean> callback)
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.SAFE_BROWSING_ALLOWLIST
.
Parameters | |
---|---|
hosts |
Set : the set of hosts for which to skip Safe Browsing checks |
callback |
ValueCallback : will be called with true if hosts are successfully added to the
allowlist, false if any hosts are malformed. The callback will be run on the UI
thread
|
setSafeBrowsingWhitelist
public static void setSafeBrowsingWhitelist (List<String> hosts, ValueCallback<Boolean> callback)
This method is deprecated.
Please use setSafeBrowsingAllowlist(Set, ValueCallback)
instead.
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.SAFE_BROWSING_WHITELIST
.
Parameters | |
---|---|
hosts |
List : the list of hosts |
callback |
ValueCallback : will be called with true if hosts are successfully added to the
allowlist. It will be called with false if any hosts are malformed. The callback
will be run on the UI thread |
setWebViewRenderProcessClient
public static void setWebViewRenderProcessClient (WebView webview, Executor executor, WebViewRenderProcessClient webViewRenderProcessClient)
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.
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.
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE
.
Parameters | |
---|---|
webview |
WebView : the WebView on which to monitor responsiveness. |
executor |
Executor : the Executor that will be used to execute callbacks. |
webViewRenderProcessClient |
WebViewRenderProcessClient : the WebViewRenderProcessClient to set for
callbacks.
|
setWebViewRenderProcessClient
public static void setWebViewRenderProcessClient (WebView webview, WebViewRenderProcessClient webViewRenderProcessClient)
Sets the renderer client object associated with this WebView.
See setWebViewRenderProcessClient(WebView, Executor, WebViewRenderProcessClient)
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
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.WEB_VIEW_RENDERER_CLIENT_BASIC_USAGE
.
Parameters | |
---|---|
webview |
WebView : the WebView on which to monitor responsiveness. |
webViewRenderProcessClient |
WebViewRenderProcessClient : the WebViewRenderProcessClient to set for
callbacks.
|
startSafeBrowsing
public static void startSafeBrowsing (Context context, ValueCallback<Boolean> callback)
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 WebSettings.setSafeBrowsingEnabled(boolean)
. 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).
This method should only be called if
WebViewFeature.isFeatureSupported(String)
returns true for WebViewFeature.START_SAFE_BROWSING
.
Parameters | |
---|---|
context |
Context : Application Context. |
callback |
ValueCallback : will be called on the UI thread with true if initialization is
successful, false otherwise.
|
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2020-09-30 UTC.