/* * 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.SystemApi; import android.annotation.Widget; import android.content.Context; 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.http.SslCertificate; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Looper; import android.os.Message; import android.os.StrictMode; import android.print.PrintDocumentAdapter; import android.security.KeyChain; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.AbsoluteLayout; import java.io.BufferedWriter; import java.io.File; import java.util.Map; /** *
A View that displays web pages. This class is the basis upon which you * can roll your own web browser or simply display some online content within your Activity. * It uses the WebKit rendering engine to display * web pages and includes methods to navigate forward and backward * through a history, zoom in and out, perform text searches and more.
*Note that, in order for your Activity to access the Internet and load web pages * in a WebView, you must add the {@code INTERNET} permissions to your * Android Manifest file:
*<uses-permission android:name="android.permission.INTERNET" />* *
This must be a child of the {@code
For more information, read * Building Web Apps in WebView.
* *By default, a WebView provides no browser-like widgets, does not * enable JavaScript and web page errors are ignored. If your goal is only * to display some HTML as a part of your UI, this is probably fine; * the user won't need to interact with the web page beyond reading * it, and the web page won't need to interact with the user. If you * actually want a full-blown web browser, then you probably want to * invoke the Browser application with a URL Intent rather than show it * with a WebView. For example: *
* Uri uri = Uri.parse("http://www.example.com");
* Intent intent = new Intent(Intent.ACTION_VIEW, uri);
* startActivity(intent);
*
* See {@link android.content.Intent} for more information.
* *To provide a WebView in your own Activity, include a {@code <WebView>} in your layout, * or set the entire Activity window as a WebView during {@link * android.app.Activity#onCreate(Bundle) onCreate()}:
** WebView webview = new WebView(this); * setContentView(webview); ** *
Then load the desired web page:
*
* // Simplest usage: note that an exception will NOT be thrown
* // if there is an error loading this page (see below).
* webview.loadUrl("http://slashdot.org/");
*
* // OR, you can also load from an HTML string:
* String summary = "<html><body>You scored <b>192</b> points.</body></html>";
* webview.loadData(summary, "text/html", null);
* // ... although note that there are restrictions on what this HTML can do.
* // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
* #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
*
*
* A WebView has several customization points where you can add your * own behavior. These are:
* *Here's a more complicated example, showing error handling, * settings, and progress notification:
* *
* // Let's display the progress in the activity title bar, like the
* // browser app does.
* getWindow().requestFeature(Window.FEATURE_PROGRESS);
*
* webview.getSettings().setJavaScriptEnabled(true);
*
* final Activity activity = this;
* webview.setWebChromeClient(new WebChromeClient() {
* public void onProgressChanged(WebView view, int progress) {
* // Activities and WebViews measure progress with different scales.
* // The progress meter will automatically disappear when we reach 100%
* activity.setProgress(progress * 1000);
* }
* });
* webview.setWebViewClient(new WebViewClient() {
* public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
* Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
* }
* });
*
* webview.loadUrl("http://developer.android.com/");
*
*
* To enable the built-in zoom, set * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}).
*NOTE: Using zoom if either the height or width is set to * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} may lead to undefined behavior * and should be avoided.
* *For obvious security reasons, your application has its own * cache, cookie store etc.—it does not share the Browser * application's data. *
* *By default, requests by the HTML to open new windows are * ignored. This is true whether they be opened by JavaScript or by * the target attribute on a link. You can customize your * {@link WebChromeClient} to provide your own behaviour for opening multiple windows, * and render them in whatever manner you want.
* *The standard behavior for an Activity is to be destroyed and * recreated when the device orientation or any other configuration changes. This will cause * the WebView to reload the current page. If you don't want that, you * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} * changes, and then just leave the WebView alone. It'll automatically * re-orient itself as appropriate. Read Handling Runtime Changes for * more information about how to handle configuration changes during runtime.
* * *The screen density of a device is based on the screen resolution. A screen with low density * has fewer available pixels per inch, where a screen with high density * has more — sometimes significantly more — pixels per inch. The density of a * screen is important because, other things being equal, a UI element (such as a button) whose * height and width are defined in terms of screen pixels will appear larger on the lower density * screen and smaller on the higher density screen. * For simplicity, Android collapses all actual screen densities into three generalized densities: * high, medium, and low.
*By default, WebView scales a web page so that it is drawn at a size that matches the default * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels * are bigger). * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS, * and meta tag features to help you (as a web developer) target screens with different screen * densities.
*Here's a summary of the features you can use to handle different screen densities:
** <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />*
The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5, * which is the high density pixel ratio.
*In order to support inline HTML5 video in your application you need to have hardware * acceleration turned on. *
* *In order to support full screen — for video or other HTML content — you need to set a * {@link android.webkit.WebChromeClient} and implement both * {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)} * and {@link WebChromeClient#onHideCustomView()}. If the implementation of either of these two methods is * missing then the web contents will not be allowed to enter full screen. Optionally you can implement * {@link WebChromeClient#getVideoLoadingProgressView()} to customize the View displayed whilst a video * is loading. *
* ** It is recommended to set the WebView layout height to a fixed value or to * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} instead of using * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}. * When using {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} * for the height none of the WebView's parents should use a * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} layout height since that could result in * incorrect sizing of the views. *
* *Setting the WebView's height to {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} * enables the following behaviors: *
* Using a layout width of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} is not * supported. If such a width is used the WebView will attempt to use the width of the parent * instead. *
* */ // 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 { /** * Broadcast Action: Indicates the data reduction proxy setting changed. * Sent by the settings app when user changes the data reduction proxy value. This intent will * always stay as a hidden API. * @hide */ @SystemApi public static final String DATA_REDUCTION_PROXY_SETTING_CHANGED = "android.webkit.DATA_REDUCTION_PROXY_SETTING_CHANGED"; private static final String LOGTAG = "WebView"; private static final boolean TRACE = false; // 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. 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(WebView webview) { mWebview = webview; } /** * Gets the WebView object. * * @return the transported WebView object */ 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 true. */ public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting); } /** * Callback interface supplied to {@link #insertVisualStateCallback} 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 id supplied to the corresponding {@link #insertVisualStateCallback} * request */ 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 null Picture. * @deprecated Deprecated due to internal changes. */ @Deprecated public void onNewPicture(WebView view, 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 null * or contain extra information about this result. * * @return additional type-dependant information about the result */ public String getExtra() { return mExtra; } } /** * Constructs a new WebView with a Context object. * * @param context a Context object used to access application assets */ public WebView(Context context) { this(context, null); } /** * Constructs a new WebView with layout parameters. * * @param context a Context object used to access application assets * @param attrs an AttributeSet passed to our parent */ public WebView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.webViewStyle); } /** * Constructs a new WebView with layout parameters and a default style. * * @param context a Context object used 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(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } /** * Constructs a new WebView with layout parameters and a default style. * * @param context a Context object used 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(Context context, 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 a Context object used 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(Context context, 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 Javscript 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 a Context object used 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. */ protected WebView(Context context, AttributeSet attrs, int defStyleAttr, Map* 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 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 'base64'. For all other values of the parameter, * including 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. For example, '#', * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively. *
* The 'data' scheme URL formed by this method uses the default US-ASCII * charset. If you need 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. * * @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(String data, String mimeType, String encoding) { checkThread(); if (TRACE) Log.d(LOGTAG, "loadData"); 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. *
* 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.
* 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.
*
* @param baseUrl the URL to use as the page's base URL. If null defaults to
* 'about:blank'.
* @param data a String of data in the given encoding
* @param mimeType the MIMEType of the data, e.g. 'text/html'. If null,
* defaults to 'text/html'.
* @param encoding the encoding of the data
* @param historyUrl the URL to use as the history entry. If null defaults
* to 'about:blank'. If non-null, this must be a valid URL.
*/
public void loadDataWithBaseURL(String baseUrl, String data,
String mimeType, String encoding, String historyUrl) {
checkThread();
if (TRACE) Log.d(LOGTAG, "loadDataWithBaseURL=" + baseUrl);
mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
}
/**
* Asynchronously evaluates JavaScript in the context of the currently displayed page.
* If non-null, |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.
*
* @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 null if no notificaion of the result is required.
*/
public void evaluateJavascript(String script, ValueCallback Updates to the the DOM are reflected asynchronously such that when the DOM is updated the
* subsequent {@link WebView#onDraw} invocation might not reflect those updates. 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.
* By current time we mean the time at which this API was called. The next draw after the
* callback completes is guaranteed to reflect all the updates to the DOM applied before the
* current time, but it may also contain updates applied after the current time. The state of the DOM covered by this API includes the following:
*
*
* It does not include the state of:
*
*
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 offscreen to avoid flickering. See 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 insertVisualStateCallback(long requestId, VisualStateCallback callback) { checkThread(); if (TRACE) Log.d(LOGTAG, "insertVisualStateCallback"); 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(); if (TRACE) Log.d(LOGTAG, "clearView"); 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. Also the * {@link android.graphics.Picture#createFromStream} and * {@link android.graphics.Picture#writeToStream} methods are not supported on the * returned object. * * @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(); if (TRACE) Log.d(LOGTAG, "capturePicture"); return mProvider.capturePicture(); } /** * @deprecated Use {@link #createPrintDocumentAdapter(String)} which requires user * to provide a print document name. */ @Deprecated public PrintDocumentAdapter createPrintDocumentAdapter() { checkThread(); if (TRACE) Log.d(LOGTAG, "createPrintDocumentAdapter"); 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} */ public PrintDocumentAdapter createPrintDocumentAdapter(String documentName) { checkThread(); if (TRACE) Log.d(LOGTAG, "createPrintDocumentAdapter"); 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 behavor * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}. * If its value is 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(); if (TRACE) Log.d(LOGTAG, "setInitialScale=" + scaleInPercent); 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(); if (TRACE) Log.d(LOGTAG, "invokeZoomPicker"); 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. */ public HitTestResult getHitTestResult() { checkThread(); if (TRACE) Log.d(LOGTAG, "getHitTestResult"); return mProvider.getHitTestResult(); } /** * Requests the anchor or image element URL at the last tapped point. * If hrefMsg is 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(Message hrefMsg) { checkThread(); if (TRACE) Log.d(LOGTAG, "requestFocusNodeHref"); 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 null. */ public void requestImageRef(Message msg) { checkThread(); if (TRACE) Log.d(LOGTAG, "requestImageRef"); 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 */ @ViewDebug.ExportedProperty(category = "webview") 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 */ @ViewDebug.ExportedProperty(category = "webview") 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 */ @ViewDebug.ExportedProperty(category = "webview") 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 */ 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 */ public String getTouchIconUrl() { return mProvider.getTouchIconUrl(); } /** * Gets the progress for the current page. * * @return the progress for the current page between 0 and 100 */ public int getProgress() { checkThread(); return mProvider.getProgress(); } /** * Gets the height of the HTML content. * * @return the height of the HTML content */ @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") 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(); if (TRACE) Log.d(LOGTAG, "pauseTimers"); mProvider.pauseTimers(); } /** * Resumes all layout, parsing, and JavaScript timers for all WebViews. * This will resume dispatching all timers. */ public void resumeTimers() { checkThread(); if (TRACE) Log.d(LOGTAG, "resumeTimers"); mProvider.resumeTimers(); } /** * Pauses any extra processing associated with this WebView and its * associated DOM, plugins, JavaScript etc. For example, if this WebView is * taken offscreen, this could be called to reduce unnecessary CPU or * network traffic. When this WebView is again "active", call onResume(). * Note that this differs from pauseTimers(), which affects all WebViews. */ public void onPause() { checkThread(); if (TRACE) Log.d(LOGTAG, "onPause"); mProvider.onPause(); } /** * Resumes a WebView after a previous call to onPause(). */ public void onResume() { checkThread(); if (TRACE) Log.d(LOGTAG, "onResume"); mProvider.onResume(); } /** * Gets whether this WebView is paused, meaning onPause() was called. * Calling onResume() sets the paused state back to false. * * @hide */ 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(); if (TRACE) Log.d(LOGTAG, "freeMemory"); 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 false, only the RAM cache is cleared */ public void clearCache(boolean includeDiskFiles) { checkThread(); if (TRACE) Log.d(LOGTAG, "clearCache"); 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(); if (TRACE) Log.d(LOGTAG, "clearFormData"); mProvider.clearFormData(); } /** * Tells this WebView to clear its internal back/forward list. */ public void clearHistory() { checkThread(); if (TRACE) Log.d(LOGTAG, "clearHistory"); mProvider.clearHistory(); } /** * Clears the SSL preferences table stored in response to proceeding with * SSL certificate errors. */ public void clearSslPreferences() { checkThread(); if (TRACE) Log.d(LOGTAG, "clearSslPreferences"); mProvider.clearSslPreferences(); } /** * Clears the client certificate preferences stored in response * to proceeding/cancelling client cert requests. Note that Webview * automatically clears these preferences when it receives a * {@link KeyChain#ACTION_STORAGE_CHANGED} intent. 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 embedder can pass null if not interested in the * callback. The runnable will be called in UI thread. */ public static void clearClientCertPreferences(Runnable onCleared) { if (TRACE) Log.d(LOGTAG, "clearClientCertPreferences"); getFactory().getStatics().clearClientCertPreferences(onCleared); } /** * Gets the WebBackForwardList for this WebView. This contains the * back/forward list for use in querying each item in the history stack. * This is a copy of the private WebBackForwardList so it contains only a * snapshot of the current state. Multiple calls to this method may return * different objects. The object returned from this method will not be * updated to reflect any new state. */ public WebBackForwardList copyBackForwardList() { checkThread(); return mProvider.copyBackForwardList(); } /** * Registers the listener to be notified as find-on-page operations * progress. This will replace the current listener. * * @param listener an implementation of {@link FindListener} */ public void setFindListener(FindListener listener) { checkThread(); setupFindListenerIfNeeded(); mFindListener.mUserFindListener = listener; } /** * Highlights and scrolls to the next match found by * {@link #findAllAsync}, wrapping around page boundaries as necessary. * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)} * has not been called yet, or if {@link #clearMatches} has been called since the * last find operation, this function does nothing. * * @param forward the direction to search * @see #setFindListener */ public void findNext(boolean forward) { checkThread(); if (TRACE) Log.d(LOGTAG, "findNext"); mProvider.findNext(forward); } /** * Finds all instances of find on the page and highlights them. * Notifies any registered {@link FindListener}. * * @param find the string to find * @return the number of occurances of the String "find" that were found * @deprecated {@link #findAllAsync} is preferred. * @see #setFindListener */ @Deprecated public int findAll(String find) { checkThread(); if (TRACE) Log.d(LOGTAG, "findAll"); StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync"); return mProvider.findAll(find); } /** * Finds all instances of find on the page and highlights them, * asynchronously. Notifies any registered {@link FindListener}. * Successive calls to this will cancel any pending searches. * * @param find the string to find. * @see #setFindListener */ public void findAllAsync(String find) { checkThread(); if (TRACE) Log.d(LOGTAG, "findAllAsync"); mProvider.findAllAsync(find); } /** * Starts an ActionMode for finding text in this WebView. Only works if this * WebView is attached to the view system. * * @param text if non-null, will be the initial text to search for. * Otherwise, the last String searched for in this WebView will * be used to start. * @param showIme if true, show the IME, assuming the user will begin typing. * If false and text is non-null, perform a find all. * @return true if the find dialog is shown, false otherwise * @deprecated This method does not work reliably on all Android versions; * implementing a custom find dialog using WebView.findAllAsync() * provides a more robust solution. */ @Deprecated public boolean showFindDialog(String text, boolean showIme) { checkThread(); if (TRACE) Log.d(LOGTAG, "showFindDialog"); return mProvider.showFindDialog(text, showIme); } /** * Gets the first substring consisting of the address of a physical * location. Currently, only addresses in the United States are detected, * and consist of: *
Note that injected objects will not * appear in JavaScript until the page is next (re)loaded. For example: *
* class JsObject {
* {@literal @}JavascriptInterface
* public String toString() { return "injectedObject"; }
* }
* webView.addJavascriptInterface(new JsObject(), "injectedObject");
* webView.loadData(" ", "text/html", null);
* webView.loadUrl("javascript:alert(injectedObject.toString())");
* * IMPORTANT: *