/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.webkit; import android.annotation.CallbackExecutor; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SystemApi; import android.annotation.Widget; import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.net.http.SslCertificate; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.os.StrictMode; import android.print.PrintDocumentAdapter; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.DragEvent; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.ViewHierarchyEncoder; import android.view.ViewStructure; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import android.view.autofill.AutofillValue; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inspector.InspectableProperty; import android.view.textclassifier.TextClassifier; import android.widget.AbsoluteLayout; import java.io.BufferedWriter; import java.io.File; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; /** * A View that displays web pages. * *
In most cases, we recommend using a standard web browser, like Chrome, to deliver * content to the user. To learn more about web browsers, read the guide on * * invoking a browser with an intent. * *
WebView objects allow you to display web content as part of your activity layout, but * lack some of the features of fully-developed browsers. A WebView is useful when * you need increased control over the UI and advanced configuration options that will allow * you to embed web pages in a specially-designed environment for your app. * *
To learn more about WebView and alternatives for serving web content, read the * documentation on * * Web-based content. * */ // Implementation notes. // The WebView is a thin API class that delegates its public API to a backend WebViewProvider // class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons. // Methods are delegated to the provider implementation: all public API methods introduced in this // file are fully delegated, whereas public and protected methods from the View base classes are // only delegated where a specific need exists for them to do so. @Widget public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler { private static final String LOGTAG = "WebView"; // Throwing an exception for incorrect thread usage if the // build target is JB MR2 or newer. Defaults to false, and is // set in the WebView constructor. @UnsupportedAppUsage private static volatile boolean sEnforceThreadChecking = false; /** * Transportation object for returning WebView across thread boundaries. */ public class WebViewTransport { private WebView mWebview; /** * Sets the WebView to the transportation object. * * @param webview the WebView to transport */ public synchronized void setWebView(@Nullable WebView webview) { mWebview = webview; } /** * Gets the WebView object. * * @return the transported WebView object */ @Nullable public synchronized WebView getWebView() { return mWebview; } } /** * URI scheme for telephone number. */ public static final String SCHEME_TEL = "tel:"; /** * URI scheme for email address. */ public static final String SCHEME_MAILTO = "mailto:"; /** * URI scheme for map address. */ public static final String SCHEME_GEO = "geo:0,0?q="; /** * Interface to listen for find results. */ public interface FindListener { /** * Notifies the listener about progress made by a find operation. * * @param activeMatchOrdinal the zero-based ordinal of the currently selected match * @param numberOfMatches how many matches have been found * @param isDoneCounting whether the find operation has actually completed. The listener * may be notified multiple times while the * operation is underway, and the numberOfMatches * value should not be considered final unless * isDoneCounting is {@code true}. */ public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting); } /** * Callback interface supplied to {@link #postVisualStateCallback} for receiving * notifications about the visual state. */ public static abstract class VisualStateCallback { /** * Invoked when the visual state is ready to be drawn in the next {@link #onDraw}. * * @param requestId The identifier passed to {@link #postVisualStateCallback} when this * callback was posted. */ public abstract void onComplete(long requestId); } /** * Interface to listen for new pictures as they change. * * @deprecated This interface is now obsolete. */ @Deprecated public interface PictureListener { /** * Used to provide notification that the WebView's picture has changed. * See {@link WebView#capturePicture} for details of the picture. * * @param view the WebView that owns the picture * @param picture the new picture. Applications targeting * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above * will always receive a {@code null} Picture. * @deprecated Deprecated due to internal changes. */ @Deprecated void onNewPicture(WebView view, @Nullable Picture picture); } public static class HitTestResult { /** * Default HitTestResult, where the target is unknown. */ public static final int UNKNOWN_TYPE = 0; /** * @deprecated This type is no longer used. */ @Deprecated public static final int ANCHOR_TYPE = 1; /** * HitTestResult for hitting a phone number. */ public static final int PHONE_TYPE = 2; /** * HitTestResult for hitting a map address. */ public static final int GEO_TYPE = 3; /** * HitTestResult for hitting an email address. */ public static final int EMAIL_TYPE = 4; /** * HitTestResult for hitting an HTML::img tag. */ public static final int IMAGE_TYPE = 5; /** * @deprecated This type is no longer used. */ @Deprecated public static final int IMAGE_ANCHOR_TYPE = 6; /** * HitTestResult for hitting a HTML::a tag with src=http. */ public static final int SRC_ANCHOR_TYPE = 7; /** * HitTestResult for hitting a HTML::a tag with src=http + HTML::img. */ public static final int SRC_IMAGE_ANCHOR_TYPE = 8; /** * HitTestResult for hitting an edit text area. */ public static final int EDIT_TEXT_TYPE = 9; private int mType; private String mExtra; /** * @hide Only for use by WebViewProvider implementations */ @SystemApi public HitTestResult() { mType = UNKNOWN_TYPE; } /** * @hide Only for use by WebViewProvider implementations */ @SystemApi public void setType(int type) { mType = type; } /** * @hide Only for use by WebViewProvider implementations */ @SystemApi public void setExtra(String extra) { mExtra = extra; } /** * Gets the type of the hit test result. See the XXX_TYPE constants * defined in this class. * * @return the type of the hit test result */ public int getType() { return mType; } /** * Gets additional type-dependant information about the result. See * {@link WebView#getHitTestResult()} for details. May either be {@code null} * or contain extra information about this result. * * @return additional type-dependant information about the result */ @Nullable public String getExtra() { return mExtra; } } /** * Constructs a new WebView with an Activity Context object. * *
Note: WebView should always be instantiated with an Activity Context.
* If instantiated with an Application Context, WebView will be unable to provide several
* features, such as JavaScript dialogs and autofill.
*
* @param context an Activity Context to access application assets
*/
public WebView(@NonNull Context context) {
this(context, null);
}
/**
* Constructs a new WebView with layout parameters.
*
* @param context an Activity Context to access application assets
* @param attrs an AttributeSet passed to our parent
*/
public WebView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.webViewStyle);
}
/**
* Constructs a new WebView with layout parameters and a default style.
*
* @param context an Activity Context to access application assets
* @param attrs an AttributeSet passed to our parent
* @param defStyleAttr an attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
*/
public WebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
/**
* Constructs a new WebView with layout parameters and a default style.
*
* @param context an Activity Context to access application assets
* @param attrs an AttributeSet passed to our parent
* @param defStyleAttr an attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param defStyleRes a resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme. Can be 0
* to not look for defaults.
*/
public WebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
this(context, attrs, defStyleAttr, defStyleRes, null, false);
}
/**
* Constructs a new WebView with layout parameters and a default style.
*
* @param context an Activity Context to access application assets
* @param attrs an AttributeSet passed to our parent
* @param defStyleAttr an attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param privateBrowsing whether this WebView will be initialized in
* private mode
*
* @deprecated Private browsing is no longer supported directly via
* WebView and will be removed in a future release. Prefer using
* {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager}
* and {@link WebStorage} for fine-grained control of privacy data.
*/
@Deprecated
public WebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr,
boolean privateBrowsing) {
this(context, attrs, defStyleAttr, 0, null, privateBrowsing);
}
/**
* Constructs a new WebView with layout parameters, a default style and a set
* of custom JavaScript interfaces to be added to this WebView at initialization
* time. This guarantees that these interfaces will be available when the JS
* context is initialized.
*
* @param context an Activity Context to access application assets
* @param attrs an AttributeSet passed to our parent
* @param defStyleAttr an attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param javaScriptInterfaces a Map of interface names, as keys, and
* object implementing those interfaces, as
* values
* @param privateBrowsing whether this WebView will be initialized in
* private mode
* @hide This is used internally by dumprendertree, as it requires the JavaScript interfaces to
* be added synchronously, before a subsequent loadUrl call takes effect.
*/
@UnsupportedAppUsage
protected WebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr,
@Nullable Map
* Also see compatibility note on {@link #evaluateJavascript}.
*
* @param url the URL of the resource to load
* @param additionalHttpHeaders the additional headers to be used in the
* HTTP request for this URL, specified as a map from name to
* value. Note that if this map contains any of the headers
* that are set by default by this WebView, such as those
* controlling caching, accept types or the User-Agent, their
* values may be overridden by this WebView's defaults.
*/
public void loadUrl(@NonNull String url, @NonNull Map
* Also see compatibility note on {@link #evaluateJavascript}.
*
* @param url the URL of the resource to load
*/
public void loadUrl(@NonNull String url) {
checkThread();
mProvider.loadUrl(url);
}
/**
* Loads the URL with postData using "POST" method into this WebView. If url
* is not a network URL, it will be loaded with {@link #loadUrl(String)}
* instead, ignoring the postData param.
*
* @param url the URL of the resource to load
* @param postData the data will be passed to "POST" request, which must be
* be "application/x-www-form-urlencoded" encoded.
*/
public void postUrl(@NonNull String url, @NonNull byte[] postData) {
checkThread();
if (URLUtil.isNetworkUrl(url)) {
mProvider.postUrl(url, postData);
} else {
mProvider.loadUrl(url);
}
}
/**
* Loads the given data into this WebView using a 'data' scheme URL.
*
* Note that JavaScript's same origin policy means that script running in a
* page loaded using this method will be unable to access content loaded
* using any scheme other than 'data', including 'http(s)'. To avoid this
* restriction, use {@link
* #loadDataWithBaseURL(String,String,String,String,String)
* loadDataWithBaseURL()} with an appropriate base URL.
*
* The {@code encoding} parameter specifies whether the data is base64 or URL
* encoded. If the data is base64 encoded, the value of the encoding
* parameter must be {@code "base64"}. HTML can be encoded with {@link
* android.util.Base64#encodeToString(byte[],int)} like so:
*
* For all other values of {@code encoding} (including {@code null}) it is assumed that the
* data uses ASCII encoding for octets inside the range of safe URL characters and use the
* standard %xx hex encoding of URLs for octets outside that range. See RFC 3986 for more information.
* Applications targeting {@link android.os.Build.VERSION_CODES#Q} or later must either use
* base64 or encode any {@code #} characters in the content as {@code %23}, otherwise they
* will be treated as the end of the content and the remaining text used as a document
* fragment identifier.
*
* The {@code mimeType} parameter specifies the format of the data.
* If WebView can't handle the specified MIME type, it will download the data.
* If {@code null}, defaults to 'text/html'.
*
* The 'data' scheme URL formed by this method uses the default US-ASCII
* charset. If you need to set a different charset, you should form a
* 'data' scheme URL which explicitly specifies a charset parameter in the
* mediatype portion of the URL and call {@link #loadUrl(String)} instead.
* Note that the charset obtained from the mediatype portion of a data URL
* always overrides that specified in the HTML or XML document itself.
*
* Content loaded using this method will have a {@code window.origin} value
* of {@code "null"}. This must not be considered to be a trusted origin
* by the application or by any JavaScript code running inside the WebView
* (for example, event sources in DOM event handlers or web messages),
* because malicious content can also create frames with a null origin. If
* you need to identify the main frame's origin in a trustworthy way, you
* should use {@link #loadDataWithBaseURL(String,String,String,String,String)
* loadDataWithBaseURL()} with a valid HTTP or HTTPS base URL to set the
* origin.
*
* @param data a String of data in the given encoding
* @param mimeType the MIME type of the data, e.g. 'text/html'.
* @param encoding the encoding of the data
*/
public void loadData(@NonNull String data, @Nullable String mimeType,
@Nullable String encoding) {
checkThread();
mProvider.loadData(data, mimeType, encoding);
}
/**
* Loads the given data into this WebView, using baseUrl as the base URL for
* the content. The base URL is used both to resolve relative URLs and when
* applying JavaScript's same origin policy. The historyUrl is used for the
* history entry.
*
* The {@code mimeType} parameter specifies the format of the data.
* If WebView can't handle the specified MIME type, it will download the data.
* If {@code null}, defaults to 'text/html'.
*
* Note that content specified in this way can access local device files
* (via 'file' scheme URLs) only if baseUrl specifies a scheme other than
* 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
*
* If the base URL uses the data scheme, this method is equivalent to
* calling {@link #loadData(String,String,String) loadData()} and the
* historyUrl is ignored, and the data will be treated as part of a data: URL,
* including the requirement that the content be URL-encoded or base64 encoded.
* If the base URL uses any other scheme, then the data will be loaded into
* the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded
* entities in the string will not be decoded.
*
* Note that the baseUrl is sent in the 'Referer' HTTP header when
* requesting subresources (images, etc.) of the page loaded using this method.
*
* If a valid HTTP or HTTPS base URL is not specified in {@code baseUrl}, then
* content loaded using this method will have a {@code window.origin} value
* of {@code "null"}. This must not be considered to be a trusted origin
* by the application or by any JavaScript code running inside the WebView
* (for example, event sources in DOM event handlers or web messages),
* because malicious content can also create frames with a null origin. If
* you need to identify the main frame's origin in a trustworthy way, you
* should use a valid HTTP or HTTPS base URL to set the origin.
*
* @param baseUrl the URL to use as the page's base URL. If {@code null} defaults to
* 'about:blank'.
* @param data a String of data in the given encoding
* @param mimeType the MIME type of the data, e.g. 'text/html'.
* @param encoding the encoding of the data
* @param historyUrl the URL to use as the history entry. If {@code null} defaults
* to 'about:blank'. If non-null, this must be a valid URL.
*/
public void loadDataWithBaseURL(@Nullable String baseUrl, @NonNull String data,
@Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) {
checkThread();
mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
}
/**
* Asynchronously evaluates JavaScript in the context of the currently displayed page.
* If non-null, {@code resultCallback} will be invoked with any result returned from that
* execution. This method must be called on the UI thread and the callback will
* be made on the UI thread.
*
* Compatibility note. Applications targeting {@link android.os.Build.VERSION_CODES#N} or
* later, JavaScript state from an empty WebView is no longer persisted across navigations like
* {@link #loadUrl(String)}. For example, global variables and functions defined before calling
* {@link #loadUrl(String)} will not exist in the loaded page. Applications should use
* {@link #addJavascriptInterface} instead to persist JavaScript objects across navigations.
*
* @param script the JavaScript to execute.
* @param resultCallback A callback to be invoked when the script execution
* completes with the result of the execution (if any).
* May be {@code null} if no notification of the result is required.
*/
public void evaluateJavascript(@NonNull String script, @Nullable ValueCallback Because updates to the DOM are processed asynchronously, updates to the DOM may not
* immediately be reflected visually by subsequent {@link WebView#onDraw} invocations. The
* {@link 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 {@link 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 {@link 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:
* To guarantee that the {@link WebView} will successfully render the first frame
* after the {@link VisualStateCallback#onComplete} method has been called a set of conditions
* must be met:
* When using this API it is also recommended to enable pre-rasterization if the {@link
* WebView} is off screen to avoid flickering. See {@link WebSettings#setOffscreenPreRaster} for
* more details and do consider its caveats.
*
* @param requestId An id that will be returned in the callback to allow callers to match
* requests with callbacks.
* @param callback The callback to be invoked.
*/
public void postVisualStateCallback(long requestId, @NonNull VisualStateCallback callback) {
checkThread();
mProvider.insertVisualStateCallback(requestId, callback);
}
/**
* Clears this WebView so that onDraw() will draw nothing but white background,
* and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY.
* @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state
* and release page resources (including any running JavaScript).
*/
@Deprecated
public void clearView() {
checkThread();
mProvider.clearView();
}
/**
* Gets a new picture that captures the current contents of this WebView.
* The picture is of the entire document being displayed, and is not
* limited to the area currently displayed by this WebView. Also, the
* picture is a static copy and is unaffected by later changes to the
* content being displayed.
*
* Note that due to internal changes, for API levels between
* {@link android.os.Build.VERSION_CODES#HONEYCOMB} and
* {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the
* picture does not include fixed position elements or scrollable divs.
*
* Note that from {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} the returned picture
* should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve
* additional conversion at a cost in memory and performance.
*
* @deprecated Use {@link #onDraw} to obtain a bitmap snapshot of the WebView, or
* {@link #saveWebArchive} to save the content to a file.
*
* @return a picture that captures the current contents of this WebView
*/
@Deprecated
public Picture capturePicture() {
checkThread();
return mProvider.capturePicture();
}
/**
* @deprecated Use {@link #createPrintDocumentAdapter(String)} which requires user
* to provide a print document name.
*/
@Deprecated
public PrintDocumentAdapter createPrintDocumentAdapter() {
checkThread();
return mProvider.createPrintDocumentAdapter("default");
}
/**
* Creates a PrintDocumentAdapter that provides the content of this WebView for printing.
*
* The adapter works by converting the WebView contents to a PDF stream. The WebView cannot
* be drawn during the conversion process - any such draws are undefined. It is recommended
* to use a dedicated off screen WebView for the printing. If necessary, an application may
* temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance
* wrapped around the object returned and observing the onStart and onFinish methods. See
* {@link android.print.PrintDocumentAdapter} for more information.
*
* @param documentName The user-facing name of the printed document. See
* {@link android.print.PrintDocumentInfo}
*/
@NonNull
public PrintDocumentAdapter createPrintDocumentAdapter(@NonNull String documentName) {
checkThread();
return mProvider.createPrintDocumentAdapter(documentName);
}
/**
* Gets the current scale of this WebView.
*
* @return the current scale
*
* @deprecated This method is prone to inaccuracy due to race conditions
* between the web rendering and UI threads; prefer
* {@link WebViewClient#onScaleChanged}.
*/
@Deprecated
@ViewDebug.ExportedProperty(category = "webview")
public float getScale() {
checkThread();
return mProvider.getScale();
}
/**
* Sets the initial scale for this WebView. 0 means default.
* The behavior for the default scale depends on the state of
* {@link WebSettings#getUseWideViewPort()} and
* {@link WebSettings#getLoadWithOverviewMode()}.
* If the content fits into the WebView control by width, then
* the zoom is set to 100%. For wide content, the behavior
* depends on the state of {@link WebSettings#getLoadWithOverviewMode()}.
* If its value is {@code true}, the content will be zoomed out to be fit
* by width into the WebView control, otherwise not.
*
* If initial scale is greater than 0, WebView starts with this value
* as initial scale.
* Please note that unlike the scale properties in the viewport meta tag,
* this method doesn't take the screen density into account.
*
* @param scaleInPercent the initial scale in percent
*/
public void setInitialScale(int scaleInPercent) {
checkThread();
mProvider.setInitialScale(scaleInPercent);
}
/**
* Invokes the graphical zoom picker widget for this WebView. This will
* result in the zoom widget appearing on the screen to control the zoom
* level of this WebView.
*/
public void invokeZoomPicker() {
checkThread();
mProvider.invokeZoomPicker();
}
/**
* Gets a HitTestResult based on the current cursor node. If a HTML::a
* tag is found and the anchor has a non-JavaScript URL, the HitTestResult
* type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field.
* If the anchor does not have a URL or if it is a JavaScript URL, the type
* will be UNKNOWN_TYPE and the URL has to be retrieved through
* {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
* found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in
* the "extra" field. A type of
* SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as
* a child node. If a phone number is found, the HitTestResult type is set
* to PHONE_TYPE and the phone number is set in the "extra" field of
* HitTestResult. If a map address is found, the HitTestResult type is set
* to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
* If an email address is found, the HitTestResult type is set to EMAIL_TYPE
* and the email is set in the "extra" field of HitTestResult. Otherwise,
* HitTestResult type is set to UNKNOWN_TYPE.
*/
@NonNull
public HitTestResult getHitTestResult() {
checkThread();
return mProvider.getHitTestResult();
}
/**
* Requests the anchor or image element URL at the last tapped point.
* If hrefMsg is {@code null}, this method returns immediately and does not
* dispatch hrefMsg to its target. If the tapped point hits an image,
* an anchor, or an image in an anchor, the message associates
* strings in named keys in its data. The value paired with the key
* may be an empty string.
*
* @param hrefMsg the message to be dispatched with the result of the
* request. The message data contains three keys. "url"
* returns the anchor's href attribute. "title" returns the
* anchor's text. "src" returns the image's src attribute.
*/
public void requestFocusNodeHref(@Nullable Message hrefMsg) {
checkThread();
mProvider.requestFocusNodeHref(hrefMsg);
}
/**
* Requests the URL of the image last touched by the user. msg will be sent
* to its target with a String representing the URL as its object.
*
* @param msg the message to be dispatched with the result of the request
* as the data member with "url" as key. The result can be {@code null}.
*/
public void requestImageRef(@NonNull Message msg) {
checkThread();
mProvider.requestImageRef(msg);
}
/**
* Gets the URL for the current page. This is not always the same as the URL
* passed to WebViewClient.onPageStarted because although the load for
* that URL has begun, the current page may not have changed.
*
* @return the URL for the current page or {@code null} if no page has been loaded
*/
@InspectableProperty(hasAttributeId = false)
@ViewDebug.ExportedProperty(category = "webview")
@Nullable
public String getUrl() {
checkThread();
return mProvider.getUrl();
}
/**
* Gets the original URL for the current page. This is not always the same
* as the URL passed to WebViewClient.onPageStarted because although the
* load for that URL has begun, the current page may not have changed.
* Also, there may have been redirects resulting in a different URL to that
* originally requested.
*
* @return the URL that was originally requested for the current page or
* {@code null} if no page has been loaded
*/
@InspectableProperty(hasAttributeId = false)
@ViewDebug.ExportedProperty(category = "webview")
@Nullable
public String getOriginalUrl() {
checkThread();
return mProvider.getOriginalUrl();
}
/**
* Gets the title for the current page. This is the title of the current page
* until WebViewClient.onReceivedTitle is called.
*
* @return the title for the current page or {@code null} if no page has been loaded
*/
@InspectableProperty(hasAttributeId = false)
@ViewDebug.ExportedProperty(category = "webview")
@Nullable
public String getTitle() {
checkThread();
return mProvider.getTitle();
}
/**
* Gets the favicon for the current page. This is the favicon of the current
* page until WebViewClient.onReceivedIcon is called.
*
* @return the favicon for the current page or {@code null} if the page doesn't
* have one or if no page has been loaded
*/
@InspectableProperty(hasAttributeId = false)
@Nullable
public Bitmap getFavicon() {
checkThread();
return mProvider.getFavicon();
}
/**
* Gets the touch icon URL for the apple-touch-icon element, or
* a URL on this site's server pointing to the standard location of a
* touch icon.
*
* @hide
*/
@UnsupportedAppUsage
public String getTouchIconUrl() {
return mProvider.getTouchIconUrl();
}
/**
* Gets the progress for the current page.
*
* @return the progress for the current page between 0 and 100
*/
@InspectableProperty(hasAttributeId = false)
public int getProgress() {
checkThread();
return mProvider.getProgress();
}
/**
* Gets the height of the HTML content.
*
* @return the height of the HTML content
*/
@InspectableProperty(hasAttributeId = false)
@ViewDebug.ExportedProperty(category = "webview")
public int getContentHeight() {
checkThread();
return mProvider.getContentHeight();
}
/**
* Gets the width of the HTML content.
*
* @return the width of the HTML content
* @hide
*/
@ViewDebug.ExportedProperty(category = "webview")
@UnsupportedAppUsage
public int getContentWidth() {
return mProvider.getContentWidth();
}
/**
* Pauses all layout, parsing, and JavaScript timers for all WebViews. This
* is a global requests, not restricted to just this WebView. This can be
* useful if the application has been paused.
*/
public void pauseTimers() {
checkThread();
mProvider.pauseTimers();
}
/**
* Resumes all layout, parsing, and JavaScript timers for all WebViews.
* This will resume dispatching all timers.
*/
public void resumeTimers() {
checkThread();
mProvider.resumeTimers();
}
/**
* Does a best-effort attempt to pause any processing that can be paused
* safely, such as animations and geolocation. Note that this call
* does not pause JavaScript. To pause JavaScript globally, use
* {@link #pauseTimers}.
*
* To resume WebView, call {@link #onResume}.
*/
public void onPause() {
checkThread();
mProvider.onPause();
}
/**
* Resumes a WebView after a previous call to {@link #onPause}.
*/
public void onResume() {
checkThread();
mProvider.onResume();
}
/**
* Gets whether this WebView is paused, meaning onPause() was called.
* Calling onResume() sets the paused state back to {@code false}.
*
* @hide
*/
@UnsupportedAppUsage
public boolean isPaused() {
return mProvider.isPaused();
}
/**
* Informs this WebView that memory is low so that it can free any available
* memory.
* @deprecated Memory caches are automatically dropped when no longer needed, and in response
* to system memory pressure.
*/
@Deprecated
public void freeMemory() {
checkThread();
mProvider.freeMemory();
}
/**
* Clears the resource cache. Note that the cache is per-application, so
* this will clear the cache for all WebViews used.
*
* @param includeDiskFiles if {@code false}, only the RAM cache is cleared
*/
public void clearCache(boolean includeDiskFiles) {
checkThread();
mProvider.clearCache(includeDiskFiles);
}
/**
* Removes the autocomplete popup from the currently focused form field, if
* present. Note this only affects the display of the autocomplete popup,
* it does not remove any saved form data from this WebView's store. To do
* that, use {@link WebViewDatabase#clearFormData}.
*/
public void clearFormData() {
checkThread();
mProvider.clearFormData();
}
/**
* Tells this WebView to clear its internal back/forward list.
*/
public void clearHistory() {
checkThread();
mProvider.clearHistory();
}
/**
* Clears the SSL preferences table stored in response to proceeding with
* SSL certificate errors.
*/
public void clearSslPreferences() {
checkThread();
mProvider.clearSslPreferences();
}
/**
* Clears the client certificate preferences stored in response
* to proceeding/cancelling client cert requests. Note that WebView
* automatically clears these preferences when the system keychain is updated.
* The preferences are shared by all the WebViews that are created by the embedder application.
*
* @param onCleared A runnable to be invoked when client certs are cleared.
* The runnable will be called in UI thread.
*/
public static void clearClientCertPreferences(@Nullable Runnable onCleared) {
getFactory().getStatics().clearClientCertPreferences(onCleared);
}
/**
* Starts Safe Browsing initialization.
*
* URL loads are not guaranteed to be protected by Safe Browsing until after {@code callback} is
* invoked with {@code true}. Safe Browsing is not fully supported on all devices. For those
* devices {@code callback} will receive {@code false}.
*
* This should not be called if Safe Browsing has been disabled by manifest tag or {@link
* WebSettings#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).
*
* @param context Application Context.
* @param callback will be called on the UI thread with {@code true} if initialization is
* successful, {@code false} otherwise.
*/
public static void startSafeBrowsing(@NonNull Context context,
@Nullable ValueCallback
* Each rule should take one of these:
*
* All other rules, including wildcards, are invalid.
*
* The correct syntax for hosts is defined by RFC 3986.
*
* @param hosts the list of hosts
* @param callback will be called with {@code true} if hosts are successfully added to the
* whitelist. It will be called with {@code false} if any hosts are malformed. The callback
* will be run on the UI thread
*/
public static void setSafeBrowsingWhitelist(@NonNull List Note: This function is deprecated and should be
* avoided on all API levels, as it cannot detect addresses outside of the
* United States and has a high rate of false positives. On API level
* {@link android.os.Build.VERSION_CODES#O_MR1} and earlier, it also causes
* the entire WebView implementation to be loaded and initialized, which
* can throw {@link android.util.AndroidRuntimeException} or other exceptions
* if the WebView implementation is currently being updated.
*
* @param addr the string to search for addresses
* @return the address, or if no address is found, {@code null}
* @deprecated This method is superseded by {@link TextClassifier#generateLinks(
* android.view.textclassifier.TextLinks.Request)}. Avoid using this method even when targeting
* API levels where no alternative is available.
*/
@Nullable
@Deprecated
public static String findAddress(String addr) {
if (addr == null) {
throw new NullPointerException("addr is null");
}
return FindAddress.findAddress(addr);
}
/**
* For apps targeting the L release, WebView has a new default behavior that reduces
* memory footprint and increases performance by intelligently choosing
* the portion of the HTML document that needs to be drawn. These
* optimizations are transparent to the developers. However, under certain
* circumstances, an App developer may want to disable them:
* In {@link android.os.Build.VERSION_CODES#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.
*
* @return the {@link WebViewRenderProcess} renderer handle associated
* with this {@link WebView}, or {@code null} if
* WebView is not runing in multiprocess mode.
*/
@Nullable
public WebViewRenderProcess getWebViewRenderProcess() {
checkThread();
return mProvider.getWebViewRenderProcess();
}
/**
* Sets the renderer client object associated with this WebView.
*
* The renderer client encapsulates callbacks relevant to WebView renderer
* state. See {@link 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 {@link 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.
*
* @param executor the Executor on which {@link WebViewRenderProcessClient}
* callbacks will execute.
* @param webViewRenderProcessClient the {@link WebViewRenderProcessClient}
* object.
*/
public void setWebViewRenderProcessClient(
@NonNull @CallbackExecutor Executor executor,
@NonNull WebViewRenderProcessClient webViewRenderProcessClient) {
checkThread();
mProvider.setWebViewRenderProcessClient(
executor, webViewRenderProcessClient);
}
/**
* Sets the renderer client object associated with this WebView.
*
* See {@link #setWebViewRenderProcessClient(Executor,WebViewRenderProcessClient)} for details.
*
* {@link WebViewRenderProcessClient} callbacks will run on the thread that this WebView was
* initialized on.
*
* @param webViewRenderProcessClient the {@link WebViewRenderProcessClient} object.
*/
public void setWebViewRenderProcessClient(
@Nullable WebViewRenderProcessClient webViewRenderProcessClient) {
checkThread();
mProvider.setWebViewRenderProcessClient(null, webViewRenderProcessClient);
}
/**
* Gets the renderer client object associated with this WebView.
*
* @return the {@link WebViewRenderProcessClient} object associated with this WebView, if one
* has been set via {@link #setWebViewRenderProcessClient(WebViewRenderProcessClient)}
* or {@code null} otherwise.
*/
@Nullable
public WebViewRenderProcessClient getWebViewRenderProcessClient() {
checkThread();
return mProvider.getWebViewRenderProcessClient();
}
/**
* Registers the interface to be used when content can not be handled by
* the rendering engine, and should be downloaded instead. This will replace
* the current handler.
*
* @param listener an implementation of DownloadListener
*/
public void setDownloadListener(@Nullable DownloadListener listener) {
checkThread();
mProvider.setDownloadListener(listener);
}
/**
* Sets the chrome handler. This is an implementation of WebChromeClient for
* use in handling JavaScript dialogs, favicons, titles, and the progress.
* This will replace the current handler.
*
* @param client an implementation of WebChromeClient
* @see #getWebChromeClient
*/
public void setWebChromeClient(@Nullable WebChromeClient client) {
checkThread();
mProvider.setWebChromeClient(client);
}
/**
* Gets the chrome handler.
*
* @return the WebChromeClient, or {@code null} if not yet set
* @see #setWebChromeClient
*/
@Nullable
public WebChromeClient getWebChromeClient() {
checkThread();
return mProvider.getWebChromeClient();
}
/**
* Sets the Picture listener. This is an interface used to receive
* notifications of a new Picture.
*
* @param listener an implementation of WebView.PictureListener
* @deprecated This method is now obsolete.
*/
@Deprecated
public void setPictureListener(PictureListener listener) {
checkThread();
mProvider.setPictureListener(listener);
}
/**
* Injects the supplied Java object into this WebView. The object is
* injected into all frames of the web page, including all the iframes,
* using the supplied name. This allows the Java object's methods to be
* accessed from JavaScript. For applications targeted to API
* level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
* and above, only public methods that are annotated with
* {@link android.webkit.JavascriptInterface} can be accessed from JavaScript.
* For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below,
* all public methods (including the inherited ones) can be accessed, see the
* important security note below for implications.
* Note that injected objects will not appear in JavaScript until the page is next
* (re)loaded. JavaScript should be enabled before injecting the object. For example:
*
* IMPORTANT:
* The returned message channels are entangled and already in started state.
*
* @return the two message ports that form the message channel.
*/
@NonNull
public WebMessagePort[] createWebMessageChannel() {
checkThread();
return mProvider.createWebMessageChannel();
}
/**
* 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.
*
* Content loaded via {@link #loadData(String,String,String)} will not have a
* valid origin, and thus cannot be sent messages securely. If you need to send
* messages using this function, you should use
* {@link #loadDataWithBaseURL(String,String,String,String,String)} with a valid
* HTTP or HTTPS {@code baseUrl} to define a valid origin that can be used for
* messaging.
*
* @param message the WebMessage
* @param targetOrigin the target origin.
*/
public void postWebMessage(@NonNull WebMessage message, @NonNull Uri targetOrigin) {
checkThread();
mProvider.postMessageToMainFrame(message, targetOrigin);
}
/**
* Gets the WebSettings object used to control the settings for this
* WebView.
*
* @return a WebSettings object that can be used to control this WebView's
* settings
*/
@NonNull
public WebSettings getSettings() {
checkThread();
return mProvider.getSettings();
}
/**
* Enables debugging of web contents (HTML / CSS / JavaScript)
* loaded into any WebViews of this application. This flag can be enabled
* in order to facilitate debugging of web layouts and JavaScript
* code running inside WebViews. Please refer to WebView documentation
* for the debugging guide.
*
* The default is {@code false}.
*
* @param enabled whether to enable web contents debugging
*/
public static void setWebContentsDebuggingEnabled(boolean enabled) {
getFactory().getStatics().setWebContentsDebuggingEnabled(enabled);
}
/**
* Gets the list of currently loaded plugins.
*
* @return the list of currently loaded plugins
* @deprecated This was used for Gears, which has been deprecated.
* @hide
*/
@Deprecated
@UnsupportedAppUsage
public static synchronized PluginList getPluginList() {
return new PluginList();
}
/**
* Define the directory used to store WebView data for the current process.
* The provided suffix will be used when constructing data and cache
* directory paths. If this API is not called, no suffix will be used.
* Each directory can be used by only one process in the application. If more
* than one process in an app wishes to use WebView, only one process can use
* the default directory, and other processes must call this API to define
* a unique suffix.
*
* This means that different processes in the same application cannot directly
* share WebView-related data, since the data directories must be distinct.
* Applications that use this API may have to explicitly pass data between
* processes. For example, login cookies may have to be copied from one
* process's cookie jar to the other using {@link CookieManager} if both
* processes' WebViews are intended to be logged in.
*
* Most applications should simply ensure that all components of the app
* that rely on WebView are in the same process, to avoid needing multiple
* data directories. The {@link #disableWebView} method can be used to ensure
* that the other processes do not use WebView by accident in this case.
*
* This API must be called before any instances of WebView are created in
* this process and before any other methods in the android.webkit package
* are called by this process.
*
* @param suffix The directory name suffix to be used for the current
* process. Must not contain a path separator.
* @throws IllegalStateException if WebView has already been initialized
* in the current process.
* @throws IllegalArgumentException if the suffix contains a path separator.
*/
public static void setDataDirectorySuffix(@NonNull String suffix) {
WebViewFactory.setDataDirectorySuffix(suffix);
}
/**
* Indicate that the current process does not intend to use WebView, and
* that an exception should be thrown if a WebView is created or any other
* methods in the android.webkit package are used.
*
* Applications with multiple processes may wish to call this in processes
* that are not intended to use WebView to avoid accidentally incurring
* the memory usage of initializing WebView in long-lived processes that
* have no need for it, and to prevent potential data directory conflicts
* (see {@link #setDataDirectorySuffix}).
*
* For example, an audio player application with one process for its
* activities and another process for its playback service may wish to call
* this method in the playback service's {@link android.app.Service#onCreate}.
*
* @throws IllegalStateException if WebView has already been initialized
* in the current process.
*/
public static void disableWebView() {
WebViewFactory.disableWebView();
}
/**
* @deprecated This was used for Gears, which has been deprecated.
* @hide
*/
@Deprecated
@UnsupportedAppUsage
public void refreshPlugins(boolean reloadOpenPages) {
checkThread();
}
/**
* Puts this WebView into text selection mode. Do not rely on this
* functionality; it will be deprecated in the future.
*
* @deprecated This method is now obsolete.
* @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}
*/
@Deprecated
@UnsupportedAppUsage
public void emulateShiftHeld() {
checkThread();
}
/**
* @deprecated WebView no longer needs to implement
* ViewGroup.OnHierarchyChangeListener. This method does nothing now.
*/
@Override
// Cannot add @hide as this can always be accessed via the interface.
@Deprecated
public void onChildViewAdded(View parent, View child) {}
/**
* @deprecated WebView no longer needs to implement
* ViewGroup.OnHierarchyChangeListener. This method does nothing now.
*/
@Override
// Cannot add @hide as this can always be accessed via the interface.
@Deprecated
public void onChildViewRemoved(View p, View child) {}
/**
* @deprecated WebView should not have implemented
* ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
*/
@Override
// Cannot add @hide as this can always be accessed via the interface.
@Deprecated
public void onGlobalFocusChanged(View oldFocus, View newFocus) {
}
/**
* @deprecated Only the default case, {@code true}, will be supported in a future version.
*/
@Deprecated
public void setMapTrackballToArrowKeys(boolean setMap) {
checkThread();
mProvider.setMapTrackballToArrowKeys(setMap);
}
public void flingScroll(int vx, int vy) {
checkThread();
mProvider.flingScroll(vx, vy);
}
/**
* Gets the zoom controls for this WebView, as a separate View. The caller
* is responsible for inserting this View into the layout hierarchy.
* The {@link ViewStructure} traditionally represents a {@link View}, while for web pages
* it represent HTML nodes. Hence, it's necessary to "map" the HTML properties in a way that is
* understood by the {@link android.service.autofill.AutofillService} implementations:
*
* If the WebView implementation can determine that the value of a field was set statically
* (for example, not through Javascript), it should also call
* {@code structure.setDataIsSensitive(false)}.
*
* For example, an HTML form with 2 fields for username and password:
*
* Would map to:
*
*
* String unencodedHtml =
* "<html><body>'%28' is the code for '('</body></html>";
* String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
* webView.loadData(encodedHtml, "text/html", "base64");
*
*
*
* It does not include the state of:
*
*
*
*
*
*
*
*
*
* 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 names must be correctly capitalized, and the zip code, if present,
* must be valid for the state. The street type must be a standard USPS
* spelling or abbreviation. The state or territory must also be spelled
* or abbreviated using USPS standards. The house number may not exceed
* five digits.
*
*
*
* Enabling drawing the entire HTML document has a significant performance
* cost. This method should be called before any WebViews are created.
*/
public static void enableSlowWholeDocumentDraw() {
getFactory().getStatics().enableSlowWholeDocumentDraw();
}
/**
* Clears the highlighting surrounding text matches created by
* {@link #findAllAsync}.
*/
public void clearMatches() {
checkThread();
mProvider.clearMatches();
}
/**
* Queries the document to see if it contains any image references. The
* message object will be dispatched with arg1 being set to 1 if images
* were found and 0 if the document does not reference any images.
*
* @param response the message that will be dispatched with the result
*/
public void documentHasImages(@NonNull Message response) {
checkThread();
mProvider.documentHasImages(response);
}
/**
* Sets the WebViewClient that will receive various notifications and
* requests. This will replace the current handler.
*
* @param client an implementation of WebViewClient
* @see #getWebViewClient
*/
public void setWebViewClient(@NonNull WebViewClient client) {
checkThread();
mProvider.setWebViewClient(client);
}
/**
* Gets the WebViewClient.
*
* @return the WebViewClient, or a default client if not yet set
* @see #setWebViewClient
*/
@NonNull
public WebViewClient getWebViewClient() {
checkThread();
return mProvider.getWebViewClient();
}
/**
* Gets a handle to the WebView renderer process associated with this WebView.
*
*
* class JsObject {
* {@literal @}JavascriptInterface
* public String toString() { return "injectedObject"; }
* }
* webview.getSettings().setJavaScriptEnabled(true);
* webView.addJavascriptInterface(new JsObject(), "injectedObject");
* webView.loadData("
*
*
*
* @param object the Java object to inject into this WebView's JavaScript
* context. {@code null} values are ignored.
* @param name the name used to expose the object in JavaScript
*/
public void addJavascriptInterface(@NonNull Object object, @NonNull String name) {
checkThread();
mProvider.addJavascriptInterface(object, name);
}
/**
* Removes a previously injected Java object from this WebView. Note that
* the removal will not be reflected in JavaScript until the page is next
* (re)loaded. See {@link #addJavascriptInterface}.
*
* @param name the name used to expose the object in JavaScript
*/
public void removeJavascriptInterface(@NonNull String name) {
checkThread();
mProvider.removeJavascriptInterface(name);
}
/**
* 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
*
*
*
*
*
*
* <label>Username:</label>
* <input type="text" name="username" id="user" value="Type your username" autocomplete="username" placeholder="Email or username">
* <label>Password:</label>
* <input type="password" name="password" id="pass" autocomplete="current-password" placeholder="Password">
*
*
*
* int index = structure.addChildCount(2);
* ViewStructure username = structure.newChild(index);
* username.setAutofillId(structure.getAutofillId(), 1); // id 1 - first child
* username.setAutofillHints("username");
* username.setHtmlInfo(username.newHtmlInfoBuilder("input")
* .addAttribute("type", "text")
* .addAttribute("name", "username")
* .addAttribute("label", "Username:")
* .build());
* username.setHint("Email or username");
* username.setAutofillType(View.AUTOFILL_TYPE_TEXT);
* username.setAutofillValue(AutofillValue.forText("Type your username"));
* // Value of the field is not sensitive because it was created statically and not changed.
* username.setDataIsSensitive(false);
*
* ViewStructure password = structure.newChild(index + 1);
* username.setAutofillId(structure, 2); // id 2 - second child
* password.setAutofillHints("current-password");
* password.setHtmlInfo(password.newHtmlInfoBuilder("input")
* .addAttribute("type", "password")
* .addAttribute("name", "password")
* .addAttribute("label", "Password:")
* .build());
* password.setHint("Password");
* password.setAutofillType(View.AUTOFILL_TYPE_TEXT);
*
*/
@Override
public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
mProvider.getViewDelegate().onProvideAutofillVirtualStructure(structure, flags);
}
@Override
public void onProvideContentCaptureStructure(@NonNull ViewStructure structure, int flags) {
mProvider.getViewDelegate().onProvideContentCaptureStructure(structure, flags);
}
@Override
public void autofill(SparseArray