WebView.java revision 6abde8b1287e4d25c89a85c40407eb26dd13d8a1
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.Nullable; 22import android.annotation.SystemApi; 23import android.annotation.Widget; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.PackageInfo; 27import android.content.res.Configuration; 28import android.graphics.Bitmap; 29import android.graphics.Canvas; 30import android.graphics.Paint; 31import android.graphics.Picture; 32import android.graphics.Rect; 33import android.graphics.drawable.Drawable; 34import android.net.Uri; 35import android.net.http.SslCertificate; 36import android.os.Build; 37import android.os.Bundle; 38import android.os.Handler; 39import android.os.Looper; 40import android.os.Message; 41import android.os.RemoteException; 42import android.os.StrictMode; 43import android.print.PrintDocumentAdapter; 44import android.security.KeyChain; 45import android.util.AttributeSet; 46import android.util.Log; 47import android.util.SparseArray; 48import android.view.DragEvent; 49import android.view.KeyEvent; 50import android.view.MotionEvent; 51import android.view.View; 52import android.view.ViewDebug; 53import android.view.ViewGroup; 54import android.view.ViewHierarchyEncoder; 55import android.view.ViewStructure; 56import android.view.ViewTreeObserver; 57import android.view.accessibility.AccessibilityEvent; 58import android.view.accessibility.AccessibilityNodeInfo; 59import android.view.accessibility.AccessibilityNodeProvider; 60import android.view.autofill.AutofillValue; 61import android.view.inputmethod.EditorInfo; 62import android.view.inputmethod.InputConnection; 63import android.view.textclassifier.TextClassifier; 64import android.widget.AbsoluteLayout; 65 66import java.io.BufferedWriter; 67import java.io.File; 68import java.lang.annotation.Retention; 69import java.lang.annotation.RetentionPolicy; 70import java.util.List; 71import java.util.Map; 72 73/** 74 * <p>A View that displays web pages. This class is the basis upon which you 75 * can roll your own web browser or simply display some online content within your Activity. 76 * It uses the WebKit rendering engine to display 77 * web pages and includes methods to navigate forward and backward 78 * through a history, zoom in and out, perform text searches and more. 79 * 80 * <p>Note that, in order for your Activity to access the Internet and load web pages 81 * in a WebView, you must add the {@code INTERNET} permissions to your 82 * Android Manifest file: 83 * 84 * <pre> 85 * {@code <uses-permission android:name="android.permission.INTERNET" />} 86 * </pre> 87 * 88 * <p>This must be a child of the <a 89 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a> 90 * element. 91 * 92 * <p>For more information, read 93 * <a href="{@docRoot}guide/webapps/webview.html">Building Web Apps in WebView</a>. 94 * 95 * <h3>Basic usage</h3> 96 * 97 * <p>By default, a WebView provides no browser-like widgets, does not 98 * enable JavaScript and web page errors are ignored. If your goal is only 99 * to display some HTML as a part of your UI, this is probably fine; 100 * the user won't need to interact with the web page beyond reading 101 * it, and the web page won't need to interact with the user. If you 102 * actually want a full-blown web browser, then you probably want to 103 * invoke the Browser application with a URL Intent rather than show it 104 * with a WebView. For example: 105 * <pre> 106 * Uri uri = Uri.parse("https://www.example.com"); 107 * Intent intent = new Intent(Intent.ACTION_VIEW, uri); 108 * startActivity(intent); 109 * </pre> 110 * <p>See {@link android.content.Intent} for more information. 111 * 112 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout, 113 * or set the entire Activity window as a WebView during {@link 114 * android.app.Activity#onCreate(Bundle) onCreate()}: 115 * 116 * <pre class="prettyprint"> 117 * WebView webview = new WebView(this); 118 * setContentView(webview); 119 * </pre> 120 * 121 * <p>Then load the desired web page: 122 * 123 * <pre> 124 * // Simplest usage: note that an exception will NOT be thrown 125 * // if there is an error loading this page (see below). 126 * webview.loadUrl("https://example.com/"); 127 * 128 * // OR, you can also load from an HTML string: 129 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 130 * webview.loadData(summary, "text/html", null); 131 * // ... although note that there are restrictions on what this HTML can do. 132 * // See {@link #loadData(String,String,String)} and {@link 133 * #loadDataWithBaseURL(String,String,String,String,String)} for more info. 134 * // Also see {@link #loadData(String,String,String)} for information on encoding special 135 * // characters. 136 * </pre> 137 * 138 * <p>A WebView has several customization points where you can add your 139 * own behavior. These are: 140 * 141 * <ul> 142 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 143 * This class is called when something that might impact a 144 * browser UI happens, for instance, progress updates and 145 * JavaScript alerts are sent here (see <a 146 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>). 147 * </li> 148 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 149 * It will be called when things happen that impact the 150 * rendering of the content, eg, errors or form submissions. You 151 * can also intercept URL loading here (via {@link 152 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String) 153 * shouldOverrideUrlLoading()}).</li> 154 * <li>Modifying the {@link android.webkit.WebSettings}, such as 155 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean) 156 * setJavaScriptEnabled()}. </li> 157 * <li>Injecting Java objects into the WebView using the 158 * {@link android.webkit.WebView#addJavascriptInterface} method. This 159 * method allows you to inject Java objects into a page's JavaScript 160 * context, so that they can be accessed by JavaScript in the page.</li> 161 * </ul> 162 * 163 * <p>Here's a more complicated example, showing error handling, 164 * settings, and progress notification: 165 * 166 * <pre class="prettyprint"> 167 * // Let's display the progress in the activity title bar, like the 168 * // browser app does. 169 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 170 * 171 * webview.getSettings().setJavaScriptEnabled(true); 172 * 173 * final Activity activity = this; 174 * webview.setWebChromeClient(new WebChromeClient() { 175 * public void onProgressChanged(WebView view, int progress) { 176 * // Activities and WebViews measure progress with different scales. 177 * // The progress meter will automatically disappear when we reach 100% 178 * activity.setProgress(progress * 1000); 179 * } 180 * }); 181 * webview.setWebViewClient(new WebViewClient() { 182 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 183 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 184 * } 185 * }); 186 * 187 * webview.loadUrl("https://developer.android.com/"); 188 * </pre> 189 * 190 * <h3>Zoom</h3> 191 * 192 * <p>To enable the built-in zoom, set 193 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 194 * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}). 195 * 196 * <p class="note"><b>Note:</b> Using zoom if either the height or width is set to 197 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} may lead to undefined behavior 198 * and should be avoided. 199 * 200 * <h3>Cookie and window management</h3> 201 * 202 * <p>For obvious security reasons, your application has its own 203 * cache, cookie store etc.—it does not share the Browser 204 * application's data. 205 * 206 * <p>By default, requests by the HTML to open new windows are 207 * ignored. This is {@code true} whether they be opened by JavaScript or by 208 * the target attribute on a link. You can customize your 209 * {@link WebChromeClient} to provide your own behavior for opening multiple windows, 210 * and render them in whatever manner you want. 211 * 212 * <p>The standard behavior for an Activity is to be destroyed and 213 * recreated when the device orientation or any other configuration changes. This will cause 214 * the WebView to reload the current page. If you don't want that, you 215 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} 216 * changes, and then just leave the WebView alone. It'll automatically 217 * re-orient itself as appropriate. Read <a 218 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for 219 * more information about how to handle configuration changes during runtime. 220 * 221 * 222 * <h3>Building web pages to support different screen densities</h3> 223 * 224 * <p>The screen density of a device is based on the screen resolution. A screen with low density 225 * has fewer available pixels per inch, where a screen with high density 226 * has more — sometimes significantly more — pixels per inch. The density of a 227 * screen is important because, other things being equal, a UI element (such as a button) whose 228 * height and width are defined in terms of screen pixels will appear larger on the lower density 229 * screen and smaller on the higher density screen. 230 * For simplicity, Android collapses all actual screen densities into three generalized densities: 231 * high, medium, and low. 232 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default 233 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen 234 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels 235 * are bigger). 236 * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS, 237 * and meta tag features to help you (as a web developer) target screens with different screen 238 * densities. 239 * <p>Here's a summary of the features you can use to handle different screen densities: 240 * <ul> 241 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the 242 * default scaling factor used for the current device. For example, if the value of {@code 243 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device 244 * and default scaling is not applied to the web page; if the value is "1.5", then the device is 245 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the 246 * value is "0.75", then the device is considered a low density device (ldpi) and the content is 247 * scaled 0.75x.</li> 248 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen 249 * densities for which this style sheet is to be used. The corresponding value should be either 250 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium 251 * density, or high density screens, respectively. For example: 252 * <pre> 253 * <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /></pre> 254 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ratio of 1.5, 255 * which is the high density pixel ratio. 256 * </li> 257 * </ul> 258 * 259 * <h3>HTML5 Video support</h3> 260 * 261 * <p>In order to support inline HTML5 video in your application you need to have hardware 262 * acceleration turned on. 263 * 264 * <h3>Full screen support</h3> 265 * 266 * <p>In order to support full screen — for video or other HTML content — you need to set a 267 * {@link android.webkit.WebChromeClient} and implement both 268 * {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)} 269 * and {@link WebChromeClient#onHideCustomView()}. If the implementation of either of these two methods is 270 * missing then the web contents will not be allowed to enter full screen. Optionally you can implement 271 * {@link WebChromeClient#getVideoLoadingProgressView()} to customize the View displayed whilst a video 272 * is loading. 273 * 274 * <h3>HTML5 Geolocation API support</h3> 275 * 276 * <p>For applications targeting Android N and later releases 277 * (API level > {@link android.os.Build.VERSION_CODES#M}) the geolocation api is only supported on 278 * secure origins such as https. For such applications requests to geolocation api on non-secure 279 * origins are automatically denied without invoking the corresponding 280 * {@link WebChromeClient#onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback)} 281 * method. 282 * 283 * <h3>Layout size</h3> 284 * <p> 285 * It is recommended to set the WebView layout height to a fixed value or to 286 * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} instead of using 287 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}. 288 * When using {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} 289 * for the height none of the WebView's parents should use a 290 * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} layout height since that could result in 291 * incorrect sizing of the views. 292 * 293 * <p>Setting the WebView's height to {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} 294 * enables the following behaviors: 295 * <ul> 296 * <li>The HTML body layout height is set to a fixed value. This means that elements with a height 297 * relative to the HTML body may not be sized correctly. </li> 298 * <li>For applications targeting {@link android.os.Build.VERSION_CODES#KITKAT} and earlier SDKs the 299 * HTML viewport meta tag will be ignored in order to preserve backwards compatibility. </li> 300 * </ul> 301 * 302 * <p> 303 * Using a layout width of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} is not 304 * supported. If such a width is used the WebView will attempt to use the width of the parent 305 * instead. 306 * 307 * <h3>Metrics</h3> 308 * 309 * <p> 310 * WebView may upload anonymous diagnostic data to Google when the user has consented. This data 311 * helps Google improve WebView. Data is collected on a per-app basis for each app which has 312 * instantiated a WebView. An individual app can opt out of this feature by putting the following 313 * tag in its manifest's {@code <application>} element: 314 * <pre> 315 * <manifest> 316 * <application> 317 * ... 318 * <meta-data android:name="android.webkit.WebView.MetricsOptOut" 319 * android:value="true" /> 320 * </application> 321 * </manifest> 322 * </pre> 323 * <p> 324 * Data will only be uploaded for a given app if the user has consented AND the app has not opted 325 * out. 326 * 327 * <h3>Safe Browsing</h3> 328 * 329 * <p> 330 * With Safe Browsing, WebView will block malicious URLs and present a warning UI to the user to 331 * allow them to navigate back safely or proceed to the malicious page. 332 * <p> 333 * Safe Browsing is enabled by default on devices which support it. If your app needs to disable 334 * Safe Browsing for all WebViews, it can do so in the manifest's {@code <application>} element: 335 * <p> 336 * <pre> 337 * <manifest> 338 * <application> 339 * ... 340 * <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing" 341 * android:value="false" /> 342 * </application> 343 * </manifest> 344 * </pre> 345 * 346 * <p> 347 * Otherwise, see {@link WebSettings#setSafeBrowsingEnabled}. 348 * 349 */ 350// Implementation notes. 351// The WebView is a thin API class that delegates its public API to a backend WebViewProvider 352// class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons. 353// Methods are delegated to the provider implementation: all public API methods introduced in this 354// file are fully delegated, whereas public and protected methods from the View base classes are 355// only delegated where a specific need exists for them to do so. 356@Widget 357public class WebView extends AbsoluteLayout 358 implements ViewTreeObserver.OnGlobalFocusChangeListener, 359 ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler { 360 361 private static final String LOGTAG = "WebView"; 362 363 // Throwing an exception for incorrect thread usage if the 364 // build target is JB MR2 or newer. Defaults to false, and is 365 // set in the WebView constructor. 366 private static volatile boolean sEnforceThreadChecking = false; 367 368 /** 369 * Transportation object for returning WebView across thread boundaries. 370 */ 371 public class WebViewTransport { 372 private WebView mWebview; 373 374 /** 375 * Sets the WebView to the transportation object. 376 * 377 * @param webview the WebView to transport 378 */ 379 public synchronized void setWebView(WebView webview) { 380 mWebview = webview; 381 } 382 383 /** 384 * Gets the WebView object. 385 * 386 * @return the transported WebView object 387 */ 388 public synchronized WebView getWebView() { 389 return mWebview; 390 } 391 } 392 393 /** 394 * URI scheme for telephone number. 395 */ 396 public static final String SCHEME_TEL = "tel:"; 397 /** 398 * URI scheme for email address. 399 */ 400 public static final String SCHEME_MAILTO = "mailto:"; 401 /** 402 * URI scheme for map address. 403 */ 404 public static final String SCHEME_GEO = "geo:0,0?q="; 405 406 /** 407 * Interface to listen for find results. 408 */ 409 public interface FindListener { 410 /** 411 * Notifies the listener about progress made by a find operation. 412 * 413 * @param activeMatchOrdinal the zero-based ordinal of the currently selected match 414 * @param numberOfMatches how many matches have been found 415 * @param isDoneCounting whether the find operation has actually completed. The listener 416 * may be notified multiple times while the 417 * operation is underway, and the numberOfMatches 418 * value should not be considered final unless 419 * isDoneCounting is {@code true}. 420 */ 421 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 422 boolean isDoneCounting); 423 } 424 425 /** 426 * Callback interface supplied to {@link #postVisualStateCallback} for receiving 427 * notifications about the visual state. 428 */ 429 public static abstract class VisualStateCallback { 430 /** 431 * Invoked when the visual state is ready to be drawn in the next {@link #onDraw}. 432 * 433 * @param requestId The identifier passed to {@link #postVisualStateCallback} when this 434 * callback was posted. 435 */ 436 public abstract void onComplete(long requestId); 437 } 438 439 /** 440 * Interface to listen for new pictures as they change. 441 * 442 * @deprecated This interface is now obsolete. 443 */ 444 @Deprecated 445 public interface PictureListener { 446 /** 447 * Used to provide notification that the WebView's picture has changed. 448 * See {@link WebView#capturePicture} for details of the picture. 449 * 450 * @param view the WebView that owns the picture 451 * @param picture the new picture. Applications targeting 452 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above 453 * will always receive a {@code null} Picture. 454 * @deprecated Deprecated due to internal changes. 455 */ 456 @Deprecated 457 void onNewPicture(WebView view, @Nullable Picture picture); 458 } 459 460 public static class HitTestResult { 461 /** 462 * Default HitTestResult, where the target is unknown. 463 */ 464 public static final int UNKNOWN_TYPE = 0; 465 /** 466 * @deprecated This type is no longer used. 467 */ 468 @Deprecated 469 public static final int ANCHOR_TYPE = 1; 470 /** 471 * HitTestResult for hitting a phone number. 472 */ 473 public static final int PHONE_TYPE = 2; 474 /** 475 * HitTestResult for hitting a map address. 476 */ 477 public static final int GEO_TYPE = 3; 478 /** 479 * HitTestResult for hitting an email address. 480 */ 481 public static final int EMAIL_TYPE = 4; 482 /** 483 * HitTestResult for hitting an HTML::img tag. 484 */ 485 public static final int IMAGE_TYPE = 5; 486 /** 487 * @deprecated This type is no longer used. 488 */ 489 @Deprecated 490 public static final int IMAGE_ANCHOR_TYPE = 6; 491 /** 492 * HitTestResult for hitting a HTML::a tag with src=http. 493 */ 494 public static final int SRC_ANCHOR_TYPE = 7; 495 /** 496 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img. 497 */ 498 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 499 /** 500 * HitTestResult for hitting an edit text area. 501 */ 502 public static final int EDIT_TEXT_TYPE = 9; 503 504 private int mType; 505 private String mExtra; 506 507 /** 508 * @hide Only for use by WebViewProvider implementations 509 */ 510 @SystemApi 511 public HitTestResult() { 512 mType = UNKNOWN_TYPE; 513 } 514 515 /** 516 * @hide Only for use by WebViewProvider implementations 517 */ 518 @SystemApi 519 public void setType(int type) { 520 mType = type; 521 } 522 523 /** 524 * @hide Only for use by WebViewProvider implementations 525 */ 526 @SystemApi 527 public void setExtra(String extra) { 528 mExtra = extra; 529 } 530 531 /** 532 * Gets the type of the hit test result. See the XXX_TYPE constants 533 * defined in this class. 534 * 535 * @return the type of the hit test result 536 */ 537 public int getType() { 538 return mType; 539 } 540 541 /** 542 * Gets additional type-dependant information about the result. See 543 * {@link WebView#getHitTestResult()} for details. May either be {@code null} 544 * or contain extra information about this result. 545 * 546 * @return additional type-dependant information about the result 547 */ 548 @Nullable 549 public String getExtra() { 550 return mExtra; 551 } 552 } 553 554 /** 555 * Constructs a new WebView with an Activity Context object. 556 * 557 * <p class="note"><b>Note:</b> WebView should always be instantiated with an Activity Context. 558 * If instantiated with an Application Context, WebView will be unable to provide several 559 * features, such as JavaScript dialogs and autofill. 560 * 561 * @param context an Activity Context to access application assets 562 */ 563 public WebView(Context context) { 564 this(context, null); 565 } 566 567 /** 568 * Constructs a new WebView with layout parameters. 569 * 570 * @param context an Activity Context to access application assets 571 * @param attrs an AttributeSet passed to our parent 572 */ 573 public WebView(Context context, AttributeSet attrs) { 574 this(context, attrs, com.android.internal.R.attr.webViewStyle); 575 } 576 577 /** 578 * Constructs a new WebView with layout parameters and a default style. 579 * 580 * @param context an Activity Context to access application assets 581 * @param attrs an AttributeSet passed to our parent 582 * @param defStyleAttr an attribute in the current theme that contains a 583 * reference to a style resource that supplies default values for 584 * the view. Can be 0 to not look for defaults. 585 */ 586 public WebView(Context context, AttributeSet attrs, int defStyleAttr) { 587 this(context, attrs, defStyleAttr, 0); 588 } 589 590 /** 591 * Constructs a new WebView with layout parameters and a default style. 592 * 593 * @param context an Activity Context to access application assets 594 * @param attrs an AttributeSet passed to our parent 595 * @param defStyleAttr an attribute in the current theme that contains a 596 * reference to a style resource that supplies default values for 597 * the view. Can be 0 to not look for defaults. 598 * @param defStyleRes a resource identifier of a style resource that 599 * supplies default values for the view, used only if 600 * defStyleAttr is 0 or can not be found in the theme. Can be 0 601 * to not look for defaults. 602 */ 603 public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 604 this(context, attrs, defStyleAttr, defStyleRes, null, false); 605 } 606 607 /** 608 * Constructs a new WebView with layout parameters and a default style. 609 * 610 * @param context an Activity Context to access application assets 611 * @param attrs an AttributeSet passed to our parent 612 * @param defStyleAttr an attribute in the current theme that contains a 613 * reference to a style resource that supplies default values for 614 * the view. Can be 0 to not look for defaults. 615 * @param privateBrowsing whether this WebView will be initialized in 616 * private mode 617 * 618 * @deprecated Private browsing is no longer supported directly via 619 * WebView and will be removed in a future release. Prefer using 620 * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager} 621 * and {@link WebStorage} for fine-grained control of privacy data. 622 */ 623 @Deprecated 624 public WebView(Context context, AttributeSet attrs, int defStyleAttr, 625 boolean privateBrowsing) { 626 this(context, attrs, defStyleAttr, 0, null, privateBrowsing); 627 } 628 629 /** 630 * Constructs a new WebView with layout parameters, a default style and a set 631 * of custom JavaScript interfaces to be added to this WebView at initialization 632 * time. This guarantees that these interfaces will be available when the JS 633 * context is initialized. 634 * 635 * @param context an Activity Context to access application assets 636 * @param attrs an AttributeSet passed to our parent 637 * @param defStyleAttr an attribute in the current theme that contains a 638 * reference to a style resource that supplies default values for 639 * the view. Can be 0 to not look for defaults. 640 * @param javaScriptInterfaces a Map of interface names, as keys, and 641 * object implementing those interfaces, as 642 * values 643 * @param privateBrowsing whether this WebView will be initialized in 644 * private mode 645 * @hide This is used internally by dumprendertree, as it requires the JavaScript interfaces to 646 * be added synchronously, before a subsequent loadUrl call takes effect. 647 */ 648 protected WebView(Context context, AttributeSet attrs, int defStyleAttr, 649 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 650 this(context, attrs, defStyleAttr, 0, javaScriptInterfaces, privateBrowsing); 651 } 652 653 /** 654 * @hide 655 */ 656 @SuppressWarnings("deprecation") // for super() call into deprecated base class constructor. 657 protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, 658 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 659 super(context, attrs, defStyleAttr, defStyleRes); 660 661 // WebView is important by default, unless app developer overrode attribute. 662 if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) { 663 setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES); 664 } 665 666 if (context == null) { 667 throw new IllegalArgumentException("Invalid context argument"); 668 } 669 if (mWebViewThread == null) { 670 throw new RuntimeException( 671 "WebView cannot be initialized on a thread that has no Looper."); 672 } 673 sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >= 674 Build.VERSION_CODES.JELLY_BEAN_MR2; 675 checkThread(); 676 677 ensureProviderCreated(); 678 mProvider.init(javaScriptInterfaces, privateBrowsing); 679 // Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed. 680 CookieSyncManager.setGetInstanceIsAllowed(); 681 } 682 683 /** 684 * Specifies whether the horizontal scrollbar has overlay style. 685 * 686 * @deprecated This method has no effect. 687 * @param overlay {@code true} if horizontal scrollbar should have overlay style 688 */ 689 @Deprecated 690 public void setHorizontalScrollbarOverlay(boolean overlay) { 691 } 692 693 /** 694 * Specifies whether the vertical scrollbar has overlay style. 695 * 696 * @deprecated This method has no effect. 697 * @param overlay {@code true} if vertical scrollbar should have overlay style 698 */ 699 @Deprecated 700 public void setVerticalScrollbarOverlay(boolean overlay) { 701 } 702 703 /** 704 * Gets whether horizontal scrollbar has overlay style. 705 * 706 * @deprecated This method is now obsolete. 707 * @return {@code true} 708 */ 709 @Deprecated 710 public boolean overlayHorizontalScrollbar() { 711 // The old implementation defaulted to true, so return true for consistency 712 return true; 713 } 714 715 /** 716 * Gets whether vertical scrollbar has overlay style. 717 * 718 * @deprecated This method is now obsolete. 719 * @return {@code false} 720 */ 721 @Deprecated 722 public boolean overlayVerticalScrollbar() { 723 // The old implementation defaulted to false, so return false for consistency 724 return false; 725 } 726 727 /** 728 * Gets the visible height (in pixels) of the embedded title bar (if any). 729 * 730 * @deprecated This method is now obsolete. 731 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 732 */ 733 @Deprecated 734 public int getVisibleTitleHeight() { 735 checkThread(); 736 return mProvider.getVisibleTitleHeight(); 737 } 738 739 /** 740 * Gets the SSL certificate for the main top-level page or {@code null} if there is 741 * no certificate (the site is not secure). 742 * 743 * @return the SSL certificate for the main top-level page 744 */ 745 @Nullable 746 public SslCertificate getCertificate() { 747 checkThread(); 748 return mProvider.getCertificate(); 749 } 750 751 /** 752 * Sets the SSL certificate for the main top-level page. 753 * 754 * @deprecated Calling this function has no useful effect, and will be 755 * ignored in future releases. 756 */ 757 @Deprecated 758 public void setCertificate(SslCertificate certificate) { 759 checkThread(); 760 mProvider.setCertificate(certificate); 761 } 762 763 //------------------------------------------------------------------------- 764 // Methods called by activity 765 //------------------------------------------------------------------------- 766 767 /** 768 * Sets a username and password pair for the specified host. This data is 769 * used by the WebView to autocomplete username and password fields in web 770 * forms. Note that this is unrelated to the credentials used for HTTP 771 * authentication. 772 * 773 * @param host the host that required the credentials 774 * @param username the username for the given host 775 * @param password the password for the given host 776 * @see WebViewDatabase#clearUsernamePassword 777 * @see WebViewDatabase#hasUsernamePassword 778 * @deprecated Saving passwords in WebView will not be supported in future versions. 779 */ 780 @Deprecated 781 public void savePassword(String host, String username, String password) { 782 checkThread(); 783 mProvider.savePassword(host, username, password); 784 } 785 786 /** 787 * Stores HTTP authentication credentials for a given host and realm to the {@link WebViewDatabase} 788 * instance. 789 * 790 * @param host the host to which the credentials apply 791 * @param realm the realm to which the credentials apply 792 * @param username the username 793 * @param password the password 794 * @deprecated Use {@link WebViewDatabase#setHttpAuthUsernamePassword} instead 795 */ 796 @Deprecated 797 public void setHttpAuthUsernamePassword(String host, String realm, 798 String username, String password) { 799 checkThread(); 800 mProvider.setHttpAuthUsernamePassword(host, realm, username, password); 801 } 802 803 /** 804 * Retrieves HTTP authentication credentials for a given host and realm from the {@link 805 * WebViewDatabase} instance. 806 * @param host the host to which the credentials apply 807 * @param realm the realm to which the credentials apply 808 * @return the credentials as a String array, if found. The first element 809 * is the username and the second element is the password. {@code null} if 810 * no credentials are found. 811 * @deprecated Use {@link WebViewDatabase#getHttpAuthUsernamePassword} instead 812 */ 813 @Deprecated 814 @Nullable 815 public String[] getHttpAuthUsernamePassword(String host, String realm) { 816 checkThread(); 817 return mProvider.getHttpAuthUsernamePassword(host, realm); 818 } 819 820 /** 821 * Destroys the internal state of this WebView. This method should be called 822 * after this WebView has been removed from the view system. No other 823 * methods may be called on this WebView after destroy. 824 */ 825 public void destroy() { 826 checkThread(); 827 mProvider.destroy(); 828 } 829 830 /** 831 * Enables platform notifications of data state and proxy changes. 832 * Notifications are enabled by default. 833 * 834 * @deprecated This method is now obsolete. 835 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 836 */ 837 @Deprecated 838 public static void enablePlatformNotifications() { 839 // noop 840 } 841 842 /** 843 * Disables platform notifications of data state and proxy changes. 844 * Notifications are enabled by default. 845 * 846 * @deprecated This method is now obsolete. 847 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 848 */ 849 @Deprecated 850 public static void disablePlatformNotifications() { 851 // noop 852 } 853 854 /** 855 * Used only by internal tests to free up memory. 856 * 857 * @hide 858 */ 859 public static void freeMemoryForTests() { 860 getFactory().getStatics().freeMemoryForTests(); 861 } 862 863 /** 864 * Informs WebView of the network state. This is used to set 865 * the JavaScript property window.navigator.isOnline and 866 * generates the online/offline event as specified in HTML5, sec. 5.7.7 867 * 868 * @param networkUp a boolean indicating if network is available 869 */ 870 public void setNetworkAvailable(boolean networkUp) { 871 checkThread(); 872 mProvider.setNetworkAvailable(networkUp); 873 } 874 875 /** 876 * Saves the state of this WebView used in 877 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 878 * method no longer stores the display data for this WebView. The previous 879 * behavior could potentially leak files if {@link #restoreState} was never 880 * called. 881 * 882 * @param outState the Bundle to store this WebView's state 883 * @return the same copy of the back/forward list used to save the state, {@code null} if the 884 * method fails. 885 */ 886 @Nullable 887 public WebBackForwardList saveState(Bundle outState) { 888 checkThread(); 889 return mProvider.saveState(outState); 890 } 891 892 /** 893 * Saves the current display data to the Bundle given. Used in conjunction 894 * with {@link #saveState}. 895 * @param b a Bundle to store the display data 896 * @param dest the file to store the serialized picture data. Will be 897 * overwritten with this WebView's picture data. 898 * @return {@code true} if the picture was successfully saved 899 * @deprecated This method is now obsolete. 900 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 901 */ 902 @Deprecated 903 public boolean savePicture(Bundle b, final File dest) { 904 checkThread(); 905 return mProvider.savePicture(b, dest); 906 } 907 908 /** 909 * Restores the display data that was saved in {@link #savePicture}. Used in 910 * conjunction with {@link #restoreState}. Note that this will not work if 911 * this WebView is hardware accelerated. 912 * 913 * @param b a Bundle containing the saved display data 914 * @param src the file where the picture data was stored 915 * @return {@code true} if the picture was successfully restored 916 * @deprecated This method is now obsolete. 917 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 918 */ 919 @Deprecated 920 public boolean restorePicture(Bundle b, File src) { 921 checkThread(); 922 return mProvider.restorePicture(b, src); 923 } 924 925 /** 926 * Restores the state of this WebView from the given Bundle. This method is 927 * intended for use in {@link android.app.Activity#onRestoreInstanceState} 928 * and should be called to restore the state of this WebView. If 929 * it is called after this WebView has had a chance to build state (load 930 * pages, create a back/forward list, etc.) there may be undesirable 931 * side-effects. Please note that this method no longer restores the 932 * display data for this WebView. 933 * 934 * @param inState the incoming Bundle of state 935 * @return the restored back/forward list or {@code null} if restoreState failed 936 */ 937 @Nullable 938 public WebBackForwardList restoreState(Bundle inState) { 939 checkThread(); 940 return mProvider.restoreState(inState); 941 } 942 943 /** 944 * Loads the given URL with the specified additional HTTP headers. 945 * <p> 946 * Also see compatibility note on {@link #evaluateJavascript}. 947 * 948 * @param url the URL of the resource to load 949 * @param additionalHttpHeaders the additional headers to be used in the 950 * HTTP request for this URL, specified as a map from name to 951 * value. Note that if this map contains any of the headers 952 * that are set by default by this WebView, such as those 953 * controlling caching, accept types or the User-Agent, their 954 * values may be overridden by this WebView's defaults. 955 */ 956 public void loadUrl(String url, Map<String, String> additionalHttpHeaders) { 957 checkThread(); 958 mProvider.loadUrl(url, additionalHttpHeaders); 959 } 960 961 /** 962 * Loads the given URL. 963 * <p> 964 * Also see compatibility note on {@link #evaluateJavascript}. 965 * 966 * @param url the URL of the resource to load 967 */ 968 public void loadUrl(String url) { 969 checkThread(); 970 mProvider.loadUrl(url); 971 } 972 973 /** 974 * Loads the URL with postData using "POST" method into this WebView. If url 975 * is not a network URL, it will be loaded with {@link #loadUrl(String)} 976 * instead, ignoring the postData param. 977 * 978 * @param url the URL of the resource to load 979 * @param postData the data will be passed to "POST" request, which must be 980 * be "application/x-www-form-urlencoded" encoded. 981 */ 982 public void postUrl(String url, byte[] postData) { 983 checkThread(); 984 if (URLUtil.isNetworkUrl(url)) { 985 mProvider.postUrl(url, postData); 986 } else { 987 mProvider.loadUrl(url); 988 } 989 } 990 991 /** 992 * Loads the given data into this WebView using a 'data' scheme URL. 993 * <p> 994 * Note that JavaScript's same origin policy means that script running in a 995 * page loaded using this method will be unable to access content loaded 996 * using any scheme other than 'data', including 'http(s)'. To avoid this 997 * restriction, use {@link 998 * #loadDataWithBaseURL(String,String,String,String,String) 999 * loadDataWithBaseURL()} with an appropriate base URL. 1000 * <p> 1001 * The {@code encoding} parameter specifies whether the data is base64 or URL 1002 * encoded. If the data is base64 encoded, the value of the encoding 1003 * parameter must be 'base64'. HTML can be encoded with {@link 1004 * android.util.Base64#encodeToString(byte[],int)} like so: 1005 * <pre> 1006 * String unencodedHtml = 1007 * "<html><body>'%28' is the code for '('</body></html>"; 1008 * String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING); 1009 * webView.loadData(encodedHtml, "text/html", "base64"); 1010 * </pre> 1011 * <p> 1012 * For all other values of {@code encoding} (including {@code null}) it is assumed that the 1013 * data uses ASCII encoding for octets inside the range of safe URL characters and use the 1014 * standard %xx hex encoding of URLs for octets outside that range. See <a 1015 * href="https://tools.ietf.org/html/rfc3986#section-2.2">RFC 3986</a> for more information. 1016 * <p> 1017 * The {@code mimeType} parameter specifies the format of the data. 1018 * If WebView can't handle the specified MIME type, it will download the data. 1019 * If {@code null}, defaults to 'text/html'. 1020 * <p> 1021 * The 'data' scheme URL formed by this method uses the default US-ASCII 1022 * charset. If you need need to set a different charset, you should form a 1023 * 'data' scheme URL which explicitly specifies a charset parameter in the 1024 * mediatype portion of the URL and call {@link #loadUrl(String)} instead. 1025 * Note that the charset obtained from the mediatype portion of a data URL 1026 * always overrides that specified in the HTML or XML document itself. 1027 * 1028 * @param data a String of data in the given encoding 1029 * @param mimeType the MIME type of the data, e.g. 'text/html'. 1030 * @param encoding the encoding of the data 1031 */ 1032 public void loadData(String data, @Nullable String mimeType, @Nullable String encoding) { 1033 checkThread(); 1034 mProvider.loadData(data, mimeType, encoding); 1035 } 1036 1037 /** 1038 * Loads the given data into this WebView, using baseUrl as the base URL for 1039 * the content. The base URL is used both to resolve relative URLs and when 1040 * applying JavaScript's same origin policy. The historyUrl is used for the 1041 * history entry. 1042 * <p> 1043 * The {@code mimeType} parameter specifies the format of the data. 1044 * If WebView can't handle the specified MIME type, it will download the data. 1045 * If {@code null}, defaults to 'text/html'. 1046 * <p> 1047 * Note that content specified in this way can access local device files 1048 * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 1049 * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'. 1050 * <p> 1051 * If the base URL uses the data scheme, this method is equivalent to 1052 * calling {@link #loadData(String,String,String) loadData()} and the 1053 * historyUrl is ignored, and the data will be treated as part of a data: URL. 1054 * If the base URL uses any other scheme, then the data will be loaded into 1055 * the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded 1056 * entities in the string will not be decoded. 1057 * <p> 1058 * Note that the baseUrl is sent in the 'Referer' HTTP header when 1059 * requesting subresources (images, etc.) of the page loaded using this method. 1060 * 1061 * @param baseUrl the URL to use as the page's base URL. If {@code null} defaults to 1062 * 'about:blank'. 1063 * @param data a String of data in the given encoding 1064 * @param mimeType the MIME type of the data, e.g. 'text/html'. 1065 * @param encoding the encoding of the data 1066 * @param historyUrl the URL to use as the history entry. If {@code null} defaults 1067 * to 'about:blank'. If non-null, this must be a valid URL. 1068 */ 1069 public void loadDataWithBaseURL(@Nullable String baseUrl, String data, 1070 @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) { 1071 checkThread(); 1072 mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); 1073 } 1074 1075 /** 1076 * Asynchronously evaluates JavaScript in the context of the currently displayed page. 1077 * If non-null, |resultCallback| will be invoked with any result returned from that 1078 * execution. This method must be called on the UI thread and the callback will 1079 * be made on the UI thread. 1080 * <p> 1081 * Compatibility note. Applications targeting {@link android.os.Build.VERSION_CODES#N} or 1082 * later, JavaScript state from an empty WebView is no longer persisted across navigations like 1083 * {@link #loadUrl(String)}. For example, global variables and functions defined before calling 1084 * {@link #loadUrl(String)} will not exist in the loaded page. Applications should use 1085 * {@link #addJavascriptInterface} instead to persist JavaScript objects across navigations. 1086 * 1087 * @param script the JavaScript to execute. 1088 * @param resultCallback A callback to be invoked when the script execution 1089 * completes with the result of the execution (if any). 1090 * May be {@code null} if no notification of the result is required. 1091 */ 1092 public void evaluateJavascript(String script, @Nullable ValueCallback<String> resultCallback) { 1093 checkThread(); 1094 mProvider.evaluateJavaScript(script, resultCallback); 1095 } 1096 1097 /** 1098 * Saves the current view as a web archive. 1099 * 1100 * @param filename the filename where the archive should be placed 1101 */ 1102 public void saveWebArchive(String filename) { 1103 checkThread(); 1104 mProvider.saveWebArchive(filename); 1105 } 1106 1107 /** 1108 * Saves the current view as a web archive. 1109 * 1110 * @param basename the filename where the archive should be placed 1111 * @param autoname if {@code false}, takes basename to be a file. If {@code true}, basename 1112 * is assumed to be a directory in which a filename will be 1113 * chosen according to the URL of the current page. 1114 * @param callback called after the web archive has been saved. The 1115 * parameter for onReceiveValue will either be the filename 1116 * under which the file was saved, or {@code null} if saving the 1117 * file failed. 1118 */ 1119 public void saveWebArchive(String basename, boolean autoname, @Nullable ValueCallback<String> 1120 callback) { 1121 checkThread(); 1122 mProvider.saveWebArchive(basename, autoname, callback); 1123 } 1124 1125 /** 1126 * Stops the current load. 1127 */ 1128 public void stopLoading() { 1129 checkThread(); 1130 mProvider.stopLoading(); 1131 } 1132 1133 /** 1134 * Reloads the current URL. 1135 */ 1136 public void reload() { 1137 checkThread(); 1138 mProvider.reload(); 1139 } 1140 1141 /** 1142 * Gets whether this WebView has a back history item. 1143 * 1144 * @return {@code true} if this WebView has a back history item 1145 */ 1146 public boolean canGoBack() { 1147 checkThread(); 1148 return mProvider.canGoBack(); 1149 } 1150 1151 /** 1152 * Goes back in the history of this WebView. 1153 */ 1154 public void goBack() { 1155 checkThread(); 1156 mProvider.goBack(); 1157 } 1158 1159 /** 1160 * Gets whether this WebView has a forward history item. 1161 * 1162 * @return {@code true} if this WebView has a forward history item 1163 */ 1164 public boolean canGoForward() { 1165 checkThread(); 1166 return mProvider.canGoForward(); 1167 } 1168 1169 /** 1170 * Goes forward in the history of this WebView. 1171 */ 1172 public void goForward() { 1173 checkThread(); 1174 mProvider.goForward(); 1175 } 1176 1177 /** 1178 * Gets whether the page can go back or forward the given 1179 * number of steps. 1180 * 1181 * @param steps the negative or positive number of steps to move the 1182 * history 1183 */ 1184 public boolean canGoBackOrForward(int steps) { 1185 checkThread(); 1186 return mProvider.canGoBackOrForward(steps); 1187 } 1188 1189 /** 1190 * Goes to the history item that is the number of steps away from 1191 * the current item. Steps is negative if backward and positive 1192 * if forward. 1193 * 1194 * @param steps the number of steps to take back or forward in the back 1195 * forward list 1196 */ 1197 public void goBackOrForward(int steps) { 1198 checkThread(); 1199 mProvider.goBackOrForward(steps); 1200 } 1201 1202 /** 1203 * Gets whether private browsing is enabled in this WebView. 1204 */ 1205 public boolean isPrivateBrowsingEnabled() { 1206 checkThread(); 1207 return mProvider.isPrivateBrowsingEnabled(); 1208 } 1209 1210 /** 1211 * Scrolls the contents of this WebView up by half the view size. 1212 * 1213 * @param top {@code true} to jump to the top of the page 1214 * @return {@code true} if the page was scrolled 1215 */ 1216 public boolean pageUp(boolean top) { 1217 checkThread(); 1218 return mProvider.pageUp(top); 1219 } 1220 1221 /** 1222 * Scrolls the contents of this WebView down by half the page size. 1223 * 1224 * @param bottom {@code true} to jump to bottom of page 1225 * @return {@code true} if the page was scrolled 1226 */ 1227 public boolean pageDown(boolean bottom) { 1228 checkThread(); 1229 return mProvider.pageDown(bottom); 1230 } 1231 1232 /** 1233 * Posts a {@link VisualStateCallback}, which will be called when 1234 * the current state of the WebView is ready to be drawn. 1235 * 1236 * <p>Because updates to the DOM are processed asynchronously, updates to the DOM may not 1237 * immediately be reflected visually by subsequent {@link WebView#onDraw} invocations. The 1238 * {@link VisualStateCallback} provides a mechanism to notify the caller when the contents of 1239 * the DOM at the current time are ready to be drawn the next time the {@link WebView} 1240 * draws. 1241 * 1242 * <p>The next draw after the callback completes is guaranteed to reflect all the updates to the 1243 * DOM up to the point at which the {@link VisualStateCallback} was posted, but it may also 1244 * contain updates applied after the callback was posted. 1245 * 1246 * <p>The state of the DOM covered by this API includes the following: 1247 * <ul> 1248 * <li>primitive HTML elements (div, img, span, etc..)</li> 1249 * <li>images</li> 1250 * <li>CSS animations</li> 1251 * <li>WebGL</li> 1252 * <li>canvas</li> 1253 * </ul> 1254 * It does not include the state of: 1255 * <ul> 1256 * <li>the video tag</li> 1257 * </ul> 1258 * 1259 * <p>To guarantee that the {@link WebView} will successfully render the first frame 1260 * after the {@link VisualStateCallback#onComplete} method has been called a set of conditions 1261 * must be met: 1262 * <ul> 1263 * <li>If the {@link WebView}'s visibility is set to {@link View#VISIBLE VISIBLE} then 1264 * the {@link WebView} must be attached to the view hierarchy.</li> 1265 * <li>If the {@link WebView}'s visibility is set to {@link View#INVISIBLE INVISIBLE} 1266 * then the {@link WebView} must be attached to the view hierarchy and must be made 1267 * {@link View#VISIBLE VISIBLE} from the {@link VisualStateCallback#onComplete} method.</li> 1268 * <li>If the {@link WebView}'s visibility is set to {@link View#GONE GONE} then the 1269 * {@link WebView} must be attached to the view hierarchy and its 1270 * {@link AbsoluteLayout.LayoutParams LayoutParams}'s width and height need to be set to fixed 1271 * values and must be made {@link View#VISIBLE VISIBLE} from the 1272 * {@link VisualStateCallback#onComplete} method.</li> 1273 * </ul> 1274 * 1275 * <p>When using this API it is also recommended to enable pre-rasterization if the {@link 1276 * WebView} is off screen to avoid flickering. See {@link WebSettings#setOffscreenPreRaster} for 1277 * more details and do consider its caveats. 1278 * 1279 * @param requestId An id that will be returned in the callback to allow callers to match 1280 * requests with callbacks. 1281 * @param callback The callback to be invoked. 1282 */ 1283 public void postVisualStateCallback(long requestId, VisualStateCallback callback) { 1284 checkThread(); 1285 mProvider.insertVisualStateCallback(requestId, callback); 1286 } 1287 1288 /** 1289 * Clears this WebView so that onDraw() will draw nothing but white background, 1290 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY. 1291 * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state 1292 * and release page resources (including any running JavaScript). 1293 */ 1294 @Deprecated 1295 public void clearView() { 1296 checkThread(); 1297 mProvider.clearView(); 1298 } 1299 1300 /** 1301 * Gets a new picture that captures the current contents of this WebView. 1302 * The picture is of the entire document being displayed, and is not 1303 * limited to the area currently displayed by this WebView. Also, the 1304 * picture is a static copy and is unaffected by later changes to the 1305 * content being displayed. 1306 * <p> 1307 * Note that due to internal changes, for API levels between 1308 * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and 1309 * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the 1310 * picture does not include fixed position elements or scrollable divs. 1311 * <p> 1312 * Note that from {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} the returned picture 1313 * should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve 1314 * additional conversion at a cost in memory and performance. Also the 1315 * {@link android.graphics.Picture#createFromStream} and 1316 * {@link android.graphics.Picture#writeToStream} methods are not supported on the 1317 * returned object. 1318 * 1319 * @deprecated Use {@link #onDraw} to obtain a bitmap snapshot of the WebView, or 1320 * {@link #saveWebArchive} to save the content to a file. 1321 * 1322 * @return a picture that captures the current contents of this WebView 1323 */ 1324 @Deprecated 1325 public Picture capturePicture() { 1326 checkThread(); 1327 return mProvider.capturePicture(); 1328 } 1329 1330 /** 1331 * @deprecated Use {@link #createPrintDocumentAdapter(String)} which requires user 1332 * to provide a print document name. 1333 */ 1334 @Deprecated 1335 public PrintDocumentAdapter createPrintDocumentAdapter() { 1336 checkThread(); 1337 return mProvider.createPrintDocumentAdapter("default"); 1338 } 1339 1340 /** 1341 * Creates a PrintDocumentAdapter that provides the content of this WebView for printing. 1342 * 1343 * The adapter works by converting the WebView contents to a PDF stream. The WebView cannot 1344 * be drawn during the conversion process - any such draws are undefined. It is recommended 1345 * to use a dedicated off screen WebView for the printing. If necessary, an application may 1346 * temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance 1347 * wrapped around the object returned and observing the onStart and onFinish methods. See 1348 * {@link android.print.PrintDocumentAdapter} for more information. 1349 * 1350 * @param documentName The user-facing name of the printed document. See 1351 * {@link android.print.PrintDocumentInfo} 1352 */ 1353 public PrintDocumentAdapter createPrintDocumentAdapter(String documentName) { 1354 checkThread(); 1355 return mProvider.createPrintDocumentAdapter(documentName); 1356 } 1357 1358 /** 1359 * Gets the current scale of this WebView. 1360 * 1361 * @return the current scale 1362 * 1363 * @deprecated This method is prone to inaccuracy due to race conditions 1364 * between the web rendering and UI threads; prefer 1365 * {@link WebViewClient#onScaleChanged}. 1366 */ 1367 @Deprecated 1368 @ViewDebug.ExportedProperty(category = "webview") 1369 public float getScale() { 1370 checkThread(); 1371 return mProvider.getScale(); 1372 } 1373 1374 /** 1375 * Sets the initial scale for this WebView. 0 means default. 1376 * The behavior for the default scale depends on the state of 1377 * {@link WebSettings#getUseWideViewPort()} and 1378 * {@link WebSettings#getLoadWithOverviewMode()}. 1379 * If the content fits into the WebView control by width, then 1380 * the zoom is set to 100%. For wide content, the behavior 1381 * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}. 1382 * If its value is {@code true}, the content will be zoomed out to be fit 1383 * by width into the WebView control, otherwise not. 1384 * 1385 * If initial scale is greater than 0, WebView starts with this value 1386 * as initial scale. 1387 * Please note that unlike the scale properties in the viewport meta tag, 1388 * this method doesn't take the screen density into account. 1389 * 1390 * @param scaleInPercent the initial scale in percent 1391 */ 1392 public void setInitialScale(int scaleInPercent) { 1393 checkThread(); 1394 mProvider.setInitialScale(scaleInPercent); 1395 } 1396 1397 /** 1398 * Invokes the graphical zoom picker widget for this WebView. This will 1399 * result in the zoom widget appearing on the screen to control the zoom 1400 * level of this WebView. 1401 */ 1402 public void invokeZoomPicker() { 1403 checkThread(); 1404 mProvider.invokeZoomPicker(); 1405 } 1406 1407 /** 1408 * Gets a HitTestResult based on the current cursor node. If a HTML::a 1409 * tag is found and the anchor has a non-JavaScript URL, the HitTestResult 1410 * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field. 1411 * If the anchor does not have a URL or if it is a JavaScript URL, the type 1412 * will be UNKNOWN_TYPE and the URL has to be retrieved through 1413 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1414 * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in 1415 * the "extra" field. A type of 1416 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as 1417 * a child node. If a phone number is found, the HitTestResult type is set 1418 * to PHONE_TYPE and the phone number is set in the "extra" field of 1419 * HitTestResult. If a map address is found, the HitTestResult type is set 1420 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1421 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1422 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1423 * HitTestResult type is set to UNKNOWN_TYPE. 1424 */ 1425 public HitTestResult getHitTestResult() { 1426 checkThread(); 1427 return mProvider.getHitTestResult(); 1428 } 1429 1430 /** 1431 * Requests the anchor or image element URL at the last tapped point. 1432 * If hrefMsg is {@code null}, this method returns immediately and does not 1433 * dispatch hrefMsg to its target. If the tapped point hits an image, 1434 * an anchor, or an image in an anchor, the message associates 1435 * strings in named keys in its data. The value paired with the key 1436 * may be an empty string. 1437 * 1438 * @param hrefMsg the message to be dispatched with the result of the 1439 * request. The message data contains three keys. "url" 1440 * returns the anchor's href attribute. "title" returns the 1441 * anchor's text. "src" returns the image's src attribute. 1442 */ 1443 public void requestFocusNodeHref(@Nullable Message hrefMsg) { 1444 checkThread(); 1445 mProvider.requestFocusNodeHref(hrefMsg); 1446 } 1447 1448 /** 1449 * Requests the URL of the image last touched by the user. msg will be sent 1450 * to its target with a String representing the URL as its object. 1451 * 1452 * @param msg the message to be dispatched with the result of the request 1453 * as the data member with "url" as key. The result can be {@code null}. 1454 */ 1455 public void requestImageRef(Message msg) { 1456 checkThread(); 1457 mProvider.requestImageRef(msg); 1458 } 1459 1460 /** 1461 * Gets the URL for the current page. This is not always the same as the URL 1462 * passed to WebViewClient.onPageStarted because although the load for 1463 * that URL has begun, the current page may not have changed. 1464 * 1465 * @return the URL for the current page 1466 */ 1467 @ViewDebug.ExportedProperty(category = "webview") 1468 public String getUrl() { 1469 checkThread(); 1470 return mProvider.getUrl(); 1471 } 1472 1473 /** 1474 * Gets the original URL for the current page. This is not always the same 1475 * as the URL passed to WebViewClient.onPageStarted because although the 1476 * load for that URL has begun, the current page may not have changed. 1477 * Also, there may have been redirects resulting in a different URL to that 1478 * originally requested. 1479 * 1480 * @return the URL that was originally requested for the current page 1481 */ 1482 @ViewDebug.ExportedProperty(category = "webview") 1483 public String getOriginalUrl() { 1484 checkThread(); 1485 return mProvider.getOriginalUrl(); 1486 } 1487 1488 /** 1489 * Gets the title for the current page. This is the title of the current page 1490 * until WebViewClient.onReceivedTitle is called. 1491 * 1492 * @return the title for the current page 1493 */ 1494 @ViewDebug.ExportedProperty(category = "webview") 1495 public String getTitle() { 1496 checkThread(); 1497 return mProvider.getTitle(); 1498 } 1499 1500 /** 1501 * Gets the favicon for the current page. This is the favicon of the current 1502 * page until WebViewClient.onReceivedIcon is called. 1503 * 1504 * @return the favicon for the current page 1505 */ 1506 public Bitmap getFavicon() { 1507 checkThread(); 1508 return mProvider.getFavicon(); 1509 } 1510 1511 /** 1512 * Gets the touch icon URL for the apple-touch-icon <link> element, or 1513 * a URL on this site's server pointing to the standard location of a 1514 * touch icon. 1515 * 1516 * @hide 1517 */ 1518 public String getTouchIconUrl() { 1519 return mProvider.getTouchIconUrl(); 1520 } 1521 1522 /** 1523 * Gets the progress for the current page. 1524 * 1525 * @return the progress for the current page between 0 and 100 1526 */ 1527 public int getProgress() { 1528 checkThread(); 1529 return mProvider.getProgress(); 1530 } 1531 1532 /** 1533 * Gets the height of the HTML content. 1534 * 1535 * @return the height of the HTML content 1536 */ 1537 @ViewDebug.ExportedProperty(category = "webview") 1538 public int getContentHeight() { 1539 checkThread(); 1540 return mProvider.getContentHeight(); 1541 } 1542 1543 /** 1544 * Gets the width of the HTML content. 1545 * 1546 * @return the width of the HTML content 1547 * @hide 1548 */ 1549 @ViewDebug.ExportedProperty(category = "webview") 1550 public int getContentWidth() { 1551 return mProvider.getContentWidth(); 1552 } 1553 1554 /** 1555 * Pauses all layout, parsing, and JavaScript timers for all WebViews. This 1556 * is a global requests, not restricted to just this WebView. This can be 1557 * useful if the application has been paused. 1558 */ 1559 public void pauseTimers() { 1560 checkThread(); 1561 mProvider.pauseTimers(); 1562 } 1563 1564 /** 1565 * Resumes all layout, parsing, and JavaScript timers for all WebViews. 1566 * This will resume dispatching all timers. 1567 */ 1568 public void resumeTimers() { 1569 checkThread(); 1570 mProvider.resumeTimers(); 1571 } 1572 1573 /** 1574 * Does a best-effort attempt to pause any processing that can be paused 1575 * safely, such as animations and geolocation. Note that this call 1576 * does not pause JavaScript. To pause JavaScript globally, use 1577 * {@link #pauseTimers}. 1578 * 1579 * To resume WebView, call {@link #onResume}. 1580 */ 1581 public void onPause() { 1582 checkThread(); 1583 mProvider.onPause(); 1584 } 1585 1586 /** 1587 * Resumes a WebView after a previous call to {@link #onPause}. 1588 */ 1589 public void onResume() { 1590 checkThread(); 1591 mProvider.onResume(); 1592 } 1593 1594 /** 1595 * Gets whether this WebView is paused, meaning onPause() was called. 1596 * Calling onResume() sets the paused state back to {@code false}. 1597 * 1598 * @hide 1599 */ 1600 public boolean isPaused() { 1601 return mProvider.isPaused(); 1602 } 1603 1604 /** 1605 * Informs this WebView that memory is low so that it can free any available 1606 * memory. 1607 * @deprecated Memory caches are automatically dropped when no longer needed, and in response 1608 * to system memory pressure. 1609 */ 1610 @Deprecated 1611 public void freeMemory() { 1612 checkThread(); 1613 mProvider.freeMemory(); 1614 } 1615 1616 /** 1617 * Clears the resource cache. Note that the cache is per-application, so 1618 * this will clear the cache for all WebViews used. 1619 * 1620 * @param includeDiskFiles if {@code false}, only the RAM cache is cleared 1621 */ 1622 public void clearCache(boolean includeDiskFiles) { 1623 checkThread(); 1624 mProvider.clearCache(includeDiskFiles); 1625 } 1626 1627 /** 1628 * Removes the autocomplete popup from the currently focused form field, if 1629 * present. Note this only affects the display of the autocomplete popup, 1630 * it does not remove any saved form data from this WebView's store. To do 1631 * that, use {@link WebViewDatabase#clearFormData}. 1632 */ 1633 public void clearFormData() { 1634 checkThread(); 1635 mProvider.clearFormData(); 1636 } 1637 1638 /** 1639 * Tells this WebView to clear its internal back/forward list. 1640 */ 1641 public void clearHistory() { 1642 checkThread(); 1643 mProvider.clearHistory(); 1644 } 1645 1646 /** 1647 * Clears the SSL preferences table stored in response to proceeding with 1648 * SSL certificate errors. 1649 */ 1650 public void clearSslPreferences() { 1651 checkThread(); 1652 mProvider.clearSslPreferences(); 1653 } 1654 1655 /** 1656 * Clears the client certificate preferences stored in response 1657 * to proceeding/cancelling client cert requests. Note that WebView 1658 * automatically clears these preferences when it receives a 1659 * {@link KeyChain#ACTION_STORAGE_CHANGED} intent. The preferences are 1660 * shared by all the WebViews that are created by the embedder application. 1661 * 1662 * @param onCleared A runnable to be invoked when client certs are cleared. 1663 * The runnable will be called in UI thread. 1664 */ 1665 public static void clearClientCertPreferences(@Nullable Runnable onCleared) { 1666 getFactory().getStatics().clearClientCertPreferences(onCleared); 1667 } 1668 1669 /** 1670 * Starts Safe Browsing initialization. 1671 * <p> 1672 * URL loads are not guaranteed to be protected by Safe Browsing until after {@code callback} is 1673 * invoked with {@code true}. Safe Browsing is not fully supported on all devices. For those 1674 * devices {@code callback} will receive {@code false}. 1675 * <p> 1676 * This should not be called if Safe Browsing has been disabled by manifest tag or {@link 1677 * WebSettings#setSafeBrowsingEnabled}. This prepares resources used for Safe Browsing. 1678 * <p> 1679 * This should be called with the Application Context (and will always use the Application 1680 * context to do its work regardless). 1681 * 1682 * @param context Application Context. 1683 * @param callback will be called on the UI thread with {@code true} if initialization is 1684 * successful, {@code false} otherwise. 1685 */ 1686 public static void startSafeBrowsing(@NonNull Context context, 1687 @Nullable ValueCallback<Boolean> callback) { 1688 getFactory().getStatics().initSafeBrowsing(context, callback); 1689 } 1690 1691 /** 1692 * Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. 1693 * The list is global for all the WebViews. 1694 * <p> 1695 * Each rule should take one of these: 1696 * <table> 1697 * <tr><th> Rule </th> <th> Example </th> <th> Matches Subdomain</th> </tr> 1698 * <tr><td> HOSTNAME </td> <td> example.com </td> <td> Yes </td> </tr> 1699 * <tr><td> .HOSTNAME </td> <td> .example.com </td> <td> No </td> </tr> 1700 * <tr><td> IPV4_LITERAL </td> <td> 192.168.1.1 </td> <td> No </td></tr> 1701 * <tr><td> IPV6_LITERAL_WITH_BRACKETS </td><td>[10:20:30:40:50:60:70:80]</td><td>No</td></tr> 1702 * </table> 1703 * <p> 1704 * All other rules, including wildcards, are invalid. 1705 * <p> 1706 * The correct syntax for hosts is defined by <a 1707 * href="https://tools.ietf.org/html/rfc3986#section-3.2.2">RFC 3986</a>. 1708 * 1709 * @param hosts the list of hosts 1710 * @param callback will be called with {@code true} if hosts are successfully added to the 1711 * whitelist. It will be called with {@code false} if any hosts are malformed. The callback 1712 * will be run on the UI thread 1713 */ 1714 public static void setSafeBrowsingWhitelist(@NonNull List<String> hosts, 1715 @Nullable ValueCallback<Boolean> callback) { 1716 getFactory().getStatics().setSafeBrowsingWhitelist(hosts, callback); 1717 } 1718 1719 /** 1720 * Returns a URL pointing to the privacy policy for Safe Browsing reporting. 1721 * 1722 * @return the url pointing to a privacy policy document which can be displayed to users. 1723 */ 1724 @NonNull 1725 public static Uri getSafeBrowsingPrivacyPolicyUrl() { 1726 return getFactory().getStatics().getSafeBrowsingPrivacyPolicyUrl(); 1727 } 1728 1729 /** 1730 * Gets the WebBackForwardList for this WebView. This contains the 1731 * back/forward list for use in querying each item in the history stack. 1732 * This is a copy of the private WebBackForwardList so it contains only a 1733 * snapshot of the current state. Multiple calls to this method may return 1734 * different objects. The object returned from this method will not be 1735 * updated to reflect any new state. 1736 */ 1737 public WebBackForwardList copyBackForwardList() { 1738 checkThread(); 1739 return mProvider.copyBackForwardList(); 1740 1741 } 1742 1743 /** 1744 * Registers the listener to be notified as find-on-page operations 1745 * progress. This will replace the current listener. 1746 * 1747 * @param listener an implementation of {@link FindListener} 1748 */ 1749 public void setFindListener(FindListener listener) { 1750 checkThread(); 1751 setupFindListenerIfNeeded(); 1752 mFindListener.mUserFindListener = listener; 1753 } 1754 1755 /** 1756 * Highlights and scrolls to the next match found by 1757 * {@link #findAllAsync}, wrapping around page boundaries as necessary. 1758 * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)} 1759 * has not been called yet, or if {@link #clearMatches} has been called since the 1760 * last find operation, this function does nothing. 1761 * 1762 * @param forward the direction to search 1763 * @see #setFindListener 1764 */ 1765 public void findNext(boolean forward) { 1766 checkThread(); 1767 mProvider.findNext(forward); 1768 } 1769 1770 /** 1771 * Finds all instances of find on the page and highlights them. 1772 * Notifies any registered {@link FindListener}. 1773 * 1774 * @param find the string to find 1775 * @return the number of occurrences of the String "find" that were found 1776 * @deprecated {@link #findAllAsync} is preferred. 1777 * @see #setFindListener 1778 */ 1779 @Deprecated 1780 public int findAll(String find) { 1781 checkThread(); 1782 StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync"); 1783 return mProvider.findAll(find); 1784 } 1785 1786 /** 1787 * Finds all instances of find on the page and highlights them, 1788 * asynchronously. Notifies any registered {@link FindListener}. 1789 * Successive calls to this will cancel any pending searches. 1790 * 1791 * @param find the string to find. 1792 * @see #setFindListener 1793 */ 1794 public void findAllAsync(String find) { 1795 checkThread(); 1796 mProvider.findAllAsync(find); 1797 } 1798 1799 /** 1800 * Starts an ActionMode for finding text in this WebView. Only works if this 1801 * WebView is attached to the view system. 1802 * 1803 * @param text if non-null, will be the initial text to search for. 1804 * Otherwise, the last String searched for in this WebView will 1805 * be used to start. 1806 * @param showIme if {@code true}, show the IME, assuming the user will begin typing. 1807 * If {@code false} and text is non-null, perform a find all. 1808 * @return {@code true} if the find dialog is shown, {@code false} otherwise 1809 * @deprecated This method does not work reliably on all Android versions; 1810 * implementing a custom find dialog using WebView.findAllAsync() 1811 * provides a more robust solution. 1812 */ 1813 @Deprecated 1814 public boolean showFindDialog(@Nullable String text, boolean showIme) { 1815 checkThread(); 1816 return mProvider.showFindDialog(text, showIme); 1817 } 1818 1819 /** 1820 * Gets the first substring consisting of the address of a physical 1821 * location. Currently, only addresses in the United States are detected, 1822 * and consist of: 1823 * <ul> 1824 * <li>a house number</li> 1825 * <li>a street name</li> 1826 * <li>a street type (Road, Circle, etc), either spelled out or 1827 * abbreviated</li> 1828 * <li>a city name</li> 1829 * <li>a state or territory, either spelled out or two-letter abbr</li> 1830 * <li>an optional 5 digit or 9 digit zip code</li> 1831 * </ul> 1832 * All names must be correctly capitalized, and the zip code, if present, 1833 * must be valid for the state. The street type must be a standard USPS 1834 * spelling or abbreviation. The state or territory must also be spelled 1835 * or abbreviated using USPS standards. The house number may not exceed 1836 * five digits. 1837 * 1838 * @param addr the string to search for addresses 1839 * @return the address, or if no address is found, {@code null} 1840 */ 1841 @Nullable 1842 public static String findAddress(String addr) { 1843 if (addr == null) { 1844 throw new NullPointerException("addr is null"); 1845 } 1846 return FindAddress.findAddress(addr); 1847 } 1848 1849 /** 1850 * For apps targeting the L release, WebView has a new default behavior that reduces 1851 * memory footprint and increases performance by intelligently choosing 1852 * the portion of the HTML document that needs to be drawn. These 1853 * optimizations are transparent to the developers. However, under certain 1854 * circumstances, an App developer may want to disable them: 1855 * <ol> 1856 * <li>When an app uses {@link #onDraw} to do own drawing and accesses portions 1857 * of the page that is way outside the visible portion of the page.</li> 1858 * <li>When an app uses {@link #capturePicture} to capture a very large HTML document. 1859 * Note that capturePicture is a deprecated API.</li> 1860 * </ol> 1861 * Enabling drawing the entire HTML document has a significant performance 1862 * cost. This method should be called before any WebViews are created. 1863 */ 1864 public static void enableSlowWholeDocumentDraw() { 1865 getFactory().getStatics().enableSlowWholeDocumentDraw(); 1866 } 1867 1868 /** 1869 * Clears the highlighting surrounding text matches created by 1870 * {@link #findAllAsync}. 1871 */ 1872 public void clearMatches() { 1873 checkThread(); 1874 mProvider.clearMatches(); 1875 } 1876 1877 /** 1878 * Queries the document to see if it contains any image references. The 1879 * message object will be dispatched with arg1 being set to 1 if images 1880 * were found and 0 if the document does not reference any images. 1881 * 1882 * @param response the message that will be dispatched with the result 1883 */ 1884 public void documentHasImages(Message response) { 1885 checkThread(); 1886 mProvider.documentHasImages(response); 1887 } 1888 1889 /** 1890 * Sets the WebViewClient that will receive various notifications and 1891 * requests. This will replace the current handler. 1892 * 1893 * @param client an implementation of WebViewClient 1894 * @see #getWebViewClient 1895 */ 1896 public void setWebViewClient(WebViewClient client) { 1897 checkThread(); 1898 mProvider.setWebViewClient(client); 1899 } 1900 1901 /** 1902 * Gets the WebViewClient. 1903 * 1904 * @return the WebViewClient, or a default client if not yet set 1905 * @see #setWebViewClient 1906 */ 1907 public WebViewClient getWebViewClient() { 1908 checkThread(); 1909 return mProvider.getWebViewClient(); 1910 } 1911 1912 /** 1913 * Registers the interface to be used when content can not be handled by 1914 * the rendering engine, and should be downloaded instead. This will replace 1915 * the current handler. 1916 * 1917 * @param listener an implementation of DownloadListener 1918 */ 1919 public void setDownloadListener(DownloadListener listener) { 1920 checkThread(); 1921 mProvider.setDownloadListener(listener); 1922 } 1923 1924 /** 1925 * Sets the chrome handler. This is an implementation of WebChromeClient for 1926 * use in handling JavaScript dialogs, favicons, titles, and the progress. 1927 * This will replace the current handler. 1928 * 1929 * @param client an implementation of WebChromeClient 1930 * @see #getWebChromeClient 1931 */ 1932 public void setWebChromeClient(WebChromeClient client) { 1933 checkThread(); 1934 mProvider.setWebChromeClient(client); 1935 } 1936 1937 /** 1938 * Gets the chrome handler. 1939 * 1940 * @return the WebChromeClient, or {@code null} if not yet set 1941 * @see #setWebChromeClient 1942 */ 1943 @Nullable 1944 public WebChromeClient getWebChromeClient() { 1945 checkThread(); 1946 return mProvider.getWebChromeClient(); 1947 } 1948 1949 /** 1950 * Sets the Picture listener. This is an interface used to receive 1951 * notifications of a new Picture. 1952 * 1953 * @param listener an implementation of WebView.PictureListener 1954 * @deprecated This method is now obsolete. 1955 */ 1956 @Deprecated 1957 public void setPictureListener(PictureListener listener) { 1958 checkThread(); 1959 mProvider.setPictureListener(listener); 1960 } 1961 1962 /** 1963 * Injects the supplied Java object into this WebView. The object is 1964 * injected into the JavaScript context of the main frame, using the 1965 * supplied name. This allows the Java object's methods to be 1966 * accessed from JavaScript. For applications targeted to API 1967 * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1968 * and above, only public methods that are annotated with 1969 * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript. 1970 * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, 1971 * all public methods (including the inherited ones) can be accessed, see the 1972 * important security note below for implications. 1973 * <p> Note that injected objects will not appear in JavaScript until the page is next 1974 * (re)loaded. JavaScript should be enabled before injecting the object. For example: 1975 * <pre> 1976 * class JsObject { 1977 * {@literal @}JavascriptInterface 1978 * public String toString() { return "injectedObject"; } 1979 * } 1980 * webview.getSettings().setJavaScriptEnabled(true); 1981 * webView.addJavascriptInterface(new JsObject(), "injectedObject"); 1982 * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null); 1983 * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre> 1984 * <p> 1985 * <strong>IMPORTANT:</strong> 1986 * <ul> 1987 * <li> This method can be used to allow JavaScript to control the host 1988 * application. This is a powerful feature, but also presents a security 1989 * risk for apps targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or earlier. 1990 * Apps that target a version later than {@link android.os.Build.VERSION_CODES#JELLY_BEAN} 1991 * are still vulnerable if the app runs on a device running Android earlier than 4.2. 1992 * The most secure way to use this method is to target {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 1993 * and to ensure the method is called only when running on Android 4.2 or later. 1994 * With these older versions, JavaScript could use reflection to access an 1995 * injected object's public fields. Use of this method in a WebView 1996 * containing untrusted content could allow an attacker to manipulate the 1997 * host application in unintended ways, executing Java code with the 1998 * permissions of the host application. Use extreme care when using this 1999 * method in a WebView which could contain untrusted content.</li> 2000 * <li> JavaScript interacts with Java object on a private, background 2001 * thread of this WebView. Care is therefore required to maintain thread 2002 * safety. 2003 * </li> 2004 * <li> The Java object's fields are not accessible.</li> 2005 * <li> For applications targeted to API level {@link android.os.Build.VERSION_CODES#LOLLIPOP} 2006 * and above, methods of injected Java objects are enumerable from 2007 * JavaScript.</li> 2008 * </ul> 2009 * 2010 * @param object the Java object to inject into this WebView's JavaScript 2011 * context. {@code null} values are ignored. 2012 * @param name the name used to expose the object in JavaScript 2013 */ 2014 public void addJavascriptInterface(Object object, String name) { 2015 checkThread(); 2016 mProvider.addJavascriptInterface(object, name); 2017 } 2018 2019 /** 2020 * Removes a previously injected Java object from this WebView. Note that 2021 * the removal will not be reflected in JavaScript until the page is next 2022 * (re)loaded. See {@link #addJavascriptInterface}. 2023 * 2024 * @param name the name used to expose the object in JavaScript 2025 */ 2026 public void removeJavascriptInterface(@NonNull String name) { 2027 checkThread(); 2028 mProvider.removeJavascriptInterface(name); 2029 } 2030 2031 /** 2032 * Creates a message channel to communicate with JS and returns the message 2033 * ports that represent the endpoints of this message channel. The HTML5 message 2034 * channel functionality is described 2035 * <a href="https://html.spec.whatwg.org/multipage/comms.html#messagechannel">here 2036 * </a> 2037 * 2038 * <p>The returned message channels are entangled and already in started state. 2039 * 2040 * @return the two message ports that form the message channel. 2041 */ 2042 public WebMessagePort[] createWebMessageChannel() { 2043 checkThread(); 2044 return mProvider.createWebMessageChannel(); 2045 } 2046 2047 /** 2048 * Post a message to main frame. The embedded application can restrict the 2049 * messages to a certain target origin. See 2050 * <a href="https://html.spec.whatwg.org/multipage/comms.html#posting-messages"> 2051 * HTML5 spec</a> for how target origin can be used. 2052 * <p> 2053 * A target origin can be set as a wildcard ("*"). However this is not recommended. 2054 * See the page above for security issues. 2055 * 2056 * @param message the WebMessage 2057 * @param targetOrigin the target origin. 2058 */ 2059 public void postWebMessage(WebMessage message, Uri targetOrigin) { 2060 checkThread(); 2061 mProvider.postMessageToMainFrame(message, targetOrigin); 2062 } 2063 2064 /** 2065 * Gets the WebSettings object used to control the settings for this 2066 * WebView. 2067 * 2068 * @return a WebSettings object that can be used to control this WebView's 2069 * settings 2070 */ 2071 public WebSettings getSettings() { 2072 checkThread(); 2073 return mProvider.getSettings(); 2074 } 2075 2076 /** 2077 * Enables debugging of web contents (HTML / CSS / JavaScript) 2078 * loaded into any WebViews of this application. This flag can be enabled 2079 * in order to facilitate debugging of web layouts and JavaScript 2080 * code running inside WebViews. Please refer to WebView documentation 2081 * for the debugging guide. 2082 * 2083 * The default is {@code false}. 2084 * 2085 * @param enabled whether to enable web contents debugging 2086 */ 2087 public static void setWebContentsDebuggingEnabled(boolean enabled) { 2088 getFactory().getStatics().setWebContentsDebuggingEnabled(enabled); 2089 } 2090 2091 /** 2092 * Gets the list of currently loaded plugins. 2093 * 2094 * @return the list of currently loaded plugins 2095 * @deprecated This was used for Gears, which has been deprecated. 2096 * @hide 2097 */ 2098 @Deprecated 2099 public static synchronized PluginList getPluginList() { 2100 return new PluginList(); 2101 } 2102 2103 /** 2104 * Define the directory used to store WebView data for the current process. 2105 * The provided suffix will be used when constructing data and cache 2106 * directory paths. If this API is not called, no suffix will be used. 2107 * Each directory can be used by only one process in the application. If more 2108 * than one process in an app wishes to use WebView, only one process can use 2109 * the default directory, and other processes must call this API to define 2110 * a unique suffix. 2111 * <p> 2112 * This means that different processes in the same application cannot directly 2113 * share WebView-related data, since the data directories must be distinct. 2114 * Applications that use this API may have to explicitly pass data between 2115 * processes. For example, login cookies may have to be copied from one 2116 * process's cookie jar to the other using {@link CookieManager} if both 2117 * processes' WebViews are intended to be logged in. 2118 * <p> 2119 * Most applications should simply ensure that all components of the app 2120 * that rely on WebView are in the same process, to avoid needing multiple 2121 * data directories. The {@link #disableWebView} method can be used to ensure 2122 * that the other processes do not use WebView by accident in this case. 2123 * <p> 2124 * This API must be called before any instances of WebView are created in 2125 * this process and before any other methods in the android.webkit package 2126 * are called by this process. 2127 * 2128 * @param suffix The directory name suffix to be used for the current 2129 * process. Must not contain a path separator. 2130 * @throws IllegalStateException if WebView has already been initialized 2131 * in the current process. 2132 * @throws IllegalArgumentException if the suffix contains a path separator. 2133 */ 2134 public static void setDataDirectorySuffix(String suffix) { 2135 WebViewFactory.setDataDirectorySuffix(suffix); 2136 } 2137 2138 /** 2139 * Indicate that the current process does not intend to use WebView, and 2140 * that an exception should be thrown if a WebView is created or any other 2141 * methods in the android.webkit package are used. 2142 * <p> 2143 * Applications with multiple processes may wish to call this in processes 2144 * that are not intended to use WebView to avoid accidentally incurring 2145 * the memory usage of initializing WebView in long-lived processes that 2146 * have no need for it, and to prevent potential data directory conflicts 2147 * (see {@link #setDataDirectorySuffix}). 2148 * <p> 2149 * For example, an audio player application with one process for its 2150 * activities and another process for its playback service may wish to call 2151 * this method in the playback service's {@link android.app.Service#onCreate}. 2152 * 2153 * @throws IllegalStateException if WebView has already been initialized 2154 * in the current process. 2155 */ 2156 public static void disableWebView() { 2157 WebViewFactory.disableWebView(); 2158 } 2159 2160 2161 /** 2162 * @deprecated This was used for Gears, which has been deprecated. 2163 * @hide 2164 */ 2165 @Deprecated 2166 public void refreshPlugins(boolean reloadOpenPages) { 2167 checkThread(); 2168 } 2169 2170 /** 2171 * Puts this WebView into text selection mode. Do not rely on this 2172 * functionality; it will be deprecated in the future. 2173 * 2174 * @deprecated This method is now obsolete. 2175 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 2176 */ 2177 @Deprecated 2178 public void emulateShiftHeld() { 2179 checkThread(); 2180 } 2181 2182 /** 2183 * @deprecated WebView no longer needs to implement 2184 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 2185 */ 2186 @Override 2187 // Cannot add @hide as this can always be accessed via the interface. 2188 @Deprecated 2189 public void onChildViewAdded(View parent, View child) {} 2190 2191 /** 2192 * @deprecated WebView no longer needs to implement 2193 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 2194 */ 2195 @Override 2196 // Cannot add @hide as this can always be accessed via the interface. 2197 @Deprecated 2198 public void onChildViewRemoved(View p, View child) {} 2199 2200 /** 2201 * @deprecated WebView should not have implemented 2202 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 2203 */ 2204 @Override 2205 // Cannot add @hide as this can always be accessed via the interface. 2206 @Deprecated 2207 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 2208 } 2209 2210 /** 2211 * @deprecated Only the default case, {@code true}, will be supported in a future version. 2212 */ 2213 @Deprecated 2214 public void setMapTrackballToArrowKeys(boolean setMap) { 2215 checkThread(); 2216 mProvider.setMapTrackballToArrowKeys(setMap); 2217 } 2218 2219 2220 public void flingScroll(int vx, int vy) { 2221 checkThread(); 2222 mProvider.flingScroll(vx, vy); 2223 } 2224 2225 /** 2226 * Gets the zoom controls for this WebView, as a separate View. The caller 2227 * is responsible for inserting this View into the layout hierarchy. 2228 * <p/> 2229 * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced 2230 * built-in zoom mechanisms for the WebView, as opposed to these separate 2231 * zoom controls. The built-in mechanisms are preferred and can be enabled 2232 * using {@link WebSettings#setBuiltInZoomControls}. 2233 * 2234 * @deprecated the built-in zoom mechanisms are preferred 2235 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} 2236 */ 2237 @Deprecated 2238 public View getZoomControls() { 2239 checkThread(); 2240 return mProvider.getZoomControls(); 2241 } 2242 2243 /** 2244 * Gets whether this WebView can be zoomed in. 2245 * 2246 * @return {@code true} if this WebView can be zoomed in 2247 * 2248 * @deprecated This method is prone to inaccuracy due to race conditions 2249 * between the web rendering and UI threads; prefer 2250 * {@link WebViewClient#onScaleChanged}. 2251 */ 2252 @Deprecated 2253 public boolean canZoomIn() { 2254 checkThread(); 2255 return mProvider.canZoomIn(); 2256 } 2257 2258 /** 2259 * Gets whether this WebView can be zoomed out. 2260 * 2261 * @return {@code true} if this WebView can be zoomed out 2262 * 2263 * @deprecated This method is prone to inaccuracy due to race conditions 2264 * between the web rendering and UI threads; prefer 2265 * {@link WebViewClient#onScaleChanged}. 2266 */ 2267 @Deprecated 2268 public boolean canZoomOut() { 2269 checkThread(); 2270 return mProvider.canZoomOut(); 2271 } 2272 2273 /** 2274 * Performs a zoom operation in this WebView. 2275 * 2276 * @param zoomFactor the zoom factor to apply. The zoom factor will be clamped to the WebView's 2277 * zoom limits. This value must be in the range 0.01 to 100.0 inclusive. 2278 */ 2279 public void zoomBy(float zoomFactor) { 2280 checkThread(); 2281 if (zoomFactor < 0.01) 2282 throw new IllegalArgumentException("zoomFactor must be greater than 0.01."); 2283 if (zoomFactor > 100.0) 2284 throw new IllegalArgumentException("zoomFactor must be less than 100."); 2285 mProvider.zoomBy(zoomFactor); 2286 } 2287 2288 /** 2289 * Performs zoom in in this WebView. 2290 * 2291 * @return {@code true} if zoom in succeeds, {@code false} if no zoom changes 2292 */ 2293 public boolean zoomIn() { 2294 checkThread(); 2295 return mProvider.zoomIn(); 2296 } 2297 2298 /** 2299 * Performs zoom out in this WebView. 2300 * 2301 * @return {@code true} if zoom out succeeds, {@code false} if no zoom changes 2302 */ 2303 public boolean zoomOut() { 2304 checkThread(); 2305 return mProvider.zoomOut(); 2306 } 2307 2308 /** 2309 * @deprecated This method is now obsolete. 2310 * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} 2311 */ 2312 @Deprecated 2313 public void debugDump() { 2314 checkThread(); 2315 } 2316 2317 /** 2318 * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)} 2319 * @hide 2320 */ 2321 @Override 2322 public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) { 2323 mProvider.dumpViewHierarchyWithProperties(out, level); 2324 } 2325 2326 /** 2327 * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)} 2328 * @hide 2329 */ 2330 @Override 2331 public View findHierarchyView(String className, int hashCode) { 2332 return mProvider.findHierarchyView(className, hashCode); 2333 } 2334 2335 /** @hide */ 2336 @IntDef(prefix = { "RENDERER_PRIORITY_" }, value = { 2337 RENDERER_PRIORITY_WAIVED, 2338 RENDERER_PRIORITY_BOUND, 2339 RENDERER_PRIORITY_IMPORTANT 2340 }) 2341 @Retention(RetentionPolicy.SOURCE) 2342 public @interface RendererPriority {} 2343 2344 /** 2345 * The renderer associated with this WebView is bound with 2346 * {@link Context#BIND_WAIVE_PRIORITY}. At this priority level 2347 * {@link WebView} renderers will be strong targets for out of memory 2348 * killing. 2349 * 2350 * Use with {@link #setRendererPriorityPolicy}. 2351 */ 2352 public static final int RENDERER_PRIORITY_WAIVED = 0; 2353 /** 2354 * The renderer associated with this WebView is bound with 2355 * the default priority for services. 2356 * 2357 * Use with {@link #setRendererPriorityPolicy}. 2358 */ 2359 public static final int RENDERER_PRIORITY_BOUND = 1; 2360 /** 2361 * The renderer associated with this WebView is bound with 2362 * {@link Context#BIND_IMPORTANT}. 2363 * 2364 * Use with {@link #setRendererPriorityPolicy}. 2365 */ 2366 public static final int RENDERER_PRIORITY_IMPORTANT = 2; 2367 2368 /** 2369 * Set the renderer priority policy for this {@link WebView}. The 2370 * priority policy will be used to determine whether an out of 2371 * process renderer should be considered to be a target for OOM 2372 * killing. 2373 * 2374 * Because a renderer can be associated with more than one 2375 * WebView, the final priority it is computed as the maximum of 2376 * any attached WebViews. When a WebView is destroyed it will 2377 * cease to be considerered when calculating the renderer 2378 * priority. Once no WebViews remain associated with the renderer, 2379 * the priority of the renderer will be reduced to 2380 * {@link #RENDERER_PRIORITY_WAIVED}. 2381 * 2382 * The default policy is to set the priority to 2383 * {@link #RENDERER_PRIORITY_IMPORTANT} regardless of visibility, 2384 * and this should not be changed unless the caller also handles 2385 * renderer crashes with 2386 * {@link WebViewClient#onRenderProcessGone}. Any other setting 2387 * will result in WebView renderers being killed by the system 2388 * more aggressively than the application. 2389 * 2390 * @param rendererRequestedPriority the minimum priority at which 2391 * this WebView desires the renderer process to be bound. 2392 * @param waivedWhenNotVisible if {@code true}, this flag specifies that 2393 * when this WebView is not visible, it will be treated as 2394 * if it had requested a priority of 2395 * {@link #RENDERER_PRIORITY_WAIVED}. 2396 */ 2397 public void setRendererPriorityPolicy( 2398 @RendererPriority int rendererRequestedPriority, 2399 boolean waivedWhenNotVisible) { 2400 mProvider.setRendererPriorityPolicy(rendererRequestedPriority, waivedWhenNotVisible); 2401 } 2402 2403 /** 2404 * Get the requested renderer priority for this WebView. 2405 * 2406 * @return the requested renderer priority policy. 2407 */ 2408 @RendererPriority 2409 public int getRendererRequestedPriority() { 2410 return mProvider.getRendererRequestedPriority(); 2411 } 2412 2413 /** 2414 * Return whether this WebView requests a priority of 2415 * {@link #RENDERER_PRIORITY_WAIVED} when not visible. 2416 * 2417 * @return whether this WebView requests a priority of 2418 * {@link #RENDERER_PRIORITY_WAIVED} when not visible. 2419 */ 2420 public boolean getRendererPriorityWaivedWhenNotVisible() { 2421 return mProvider.getRendererPriorityWaivedWhenNotVisible(); 2422 } 2423 2424 /** 2425 * Sets the {@link TextClassifier} for this WebView. 2426 */ 2427 public void setTextClassifier(@Nullable TextClassifier textClassifier) { 2428 mProvider.setTextClassifier(textClassifier); 2429 } 2430 2431 /** 2432 * Returns the {@link TextClassifier} used by this WebView. 2433 * If no TextClassifier has been set, this WebView uses the default set by the system. 2434 */ 2435 @NonNull 2436 public TextClassifier getTextClassifier() { 2437 return mProvider.getTextClassifier(); 2438 } 2439 2440 /** 2441 * Returns the {@link ClassLoader} used to load internal WebView classes. 2442 * This method is meant for use by the WebView Support Library, there is no reason to use this 2443 * method otherwise. 2444 */ 2445 @NonNull 2446 public static ClassLoader getWebViewClassLoader() { 2447 return getFactory().getWebViewClassLoader(); 2448 } 2449 2450 /** 2451 * Returns the {@link Looper} corresponding to the thread on which WebView calls must be made. 2452 */ 2453 @NonNull 2454 public Looper getWebViewLooper() { 2455 return mWebViewThread; 2456 } 2457 2458 /** 2459 * Returns the {@link Looper} corresponding to the thread on which WebView calls must be made. 2460 */ 2461 @NonNull 2462 public Looper getLooper() { 2463 return mWebViewThread; 2464 } 2465 2466 //------------------------------------------------------------------------- 2467 // Interface for WebView providers 2468 //------------------------------------------------------------------------- 2469 2470 /** 2471 * Gets the WebViewProvider. Used by providers to obtain the underlying 2472 * implementation, e.g. when the application responds to 2473 * WebViewClient.onCreateWindow() request. 2474 * 2475 * @hide WebViewProvider is not public API. 2476 */ 2477 @SystemApi 2478 public WebViewProvider getWebViewProvider() { 2479 return mProvider; 2480 } 2481 2482 /** 2483 * Callback interface, allows the provider implementation to access non-public methods 2484 * and fields, and make super-class calls in this WebView instance. 2485 * @hide Only for use by WebViewProvider implementations 2486 */ 2487 @SystemApi 2488 public class PrivateAccess { 2489 // ---- Access to super-class methods ---- 2490 public int super_getScrollBarStyle() { 2491 return WebView.super.getScrollBarStyle(); 2492 } 2493 2494 public void super_scrollTo(int scrollX, int scrollY) { 2495 WebView.super.scrollTo(scrollX, scrollY); 2496 } 2497 2498 public void super_computeScroll() { 2499 WebView.super.computeScroll(); 2500 } 2501 2502 public boolean super_onHoverEvent(MotionEvent event) { 2503 return WebView.super.onHoverEvent(event); 2504 } 2505 2506 public boolean super_performAccessibilityAction(int action, Bundle arguments) { 2507 return WebView.super.performAccessibilityActionInternal(action, arguments); 2508 } 2509 2510 public boolean super_performLongClick() { 2511 return WebView.super.performLongClick(); 2512 } 2513 2514 public boolean super_setFrame(int left, int top, int right, int bottom) { 2515 return WebView.super.setFrame(left, top, right, bottom); 2516 } 2517 2518 public boolean super_dispatchKeyEvent(KeyEvent event) { 2519 return WebView.super.dispatchKeyEvent(event); 2520 } 2521 2522 public boolean super_onGenericMotionEvent(MotionEvent event) { 2523 return WebView.super.onGenericMotionEvent(event); 2524 } 2525 2526 public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) { 2527 return WebView.super.requestFocus(direction, previouslyFocusedRect); 2528 } 2529 2530 public void super_setLayoutParams(ViewGroup.LayoutParams params) { 2531 WebView.super.setLayoutParams(params); 2532 } 2533 2534 public void super_startActivityForResult(Intent intent, int requestCode) { 2535 WebView.super.startActivityForResult(intent, requestCode); 2536 } 2537 2538 // ---- Access to non-public methods ---- 2539 public void overScrollBy(int deltaX, int deltaY, 2540 int scrollX, int scrollY, 2541 int scrollRangeX, int scrollRangeY, 2542 int maxOverScrollX, int maxOverScrollY, 2543 boolean isTouchEvent) { 2544 WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, 2545 maxOverScrollX, maxOverScrollY, isTouchEvent); 2546 } 2547 2548 public void awakenScrollBars(int duration) { 2549 WebView.this.awakenScrollBars(duration); 2550 } 2551 2552 public void awakenScrollBars(int duration, boolean invalidate) { 2553 WebView.this.awakenScrollBars(duration, invalidate); 2554 } 2555 2556 public float getVerticalScrollFactor() { 2557 return WebView.this.getVerticalScrollFactor(); 2558 } 2559 2560 public float getHorizontalScrollFactor() { 2561 return WebView.this.getHorizontalScrollFactor(); 2562 } 2563 2564 public void setMeasuredDimension(int measuredWidth, int measuredHeight) { 2565 WebView.this.setMeasuredDimension(measuredWidth, measuredHeight); 2566 } 2567 2568 public void onScrollChanged(int l, int t, int oldl, int oldt) { 2569 WebView.this.onScrollChanged(l, t, oldl, oldt); 2570 } 2571 2572 public int getHorizontalScrollbarHeight() { 2573 return WebView.this.getHorizontalScrollbarHeight(); 2574 } 2575 2576 public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2577 int l, int t, int r, int b) { 2578 WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2579 } 2580 2581 // ---- Access to (non-public) fields ---- 2582 /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */ 2583 public void setScrollXRaw(int scrollX) { 2584 WebView.this.mScrollX = scrollX; 2585 } 2586 2587 /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */ 2588 public void setScrollYRaw(int scrollY) { 2589 WebView.this.mScrollY = scrollY; 2590 } 2591 2592 } 2593 2594 //------------------------------------------------------------------------- 2595 // Package-private internal stuff 2596 //------------------------------------------------------------------------- 2597 2598 // Only used by android.webkit.FindActionModeCallback. 2599 void setFindDialogFindListener(FindListener listener) { 2600 checkThread(); 2601 setupFindListenerIfNeeded(); 2602 mFindListener.mFindDialogFindListener = listener; 2603 } 2604 2605 // Only used by android.webkit.FindActionModeCallback. 2606 void notifyFindDialogDismissed() { 2607 checkThread(); 2608 mProvider.notifyFindDialogDismissed(); 2609 } 2610 2611 //------------------------------------------------------------------------- 2612 // Private internal stuff 2613 //------------------------------------------------------------------------- 2614 2615 private WebViewProvider mProvider; 2616 2617 /** 2618 * In addition to the FindListener that the user may set via the WebView.setFindListener 2619 * API, FindActionModeCallback will register it's own FindListener. We keep them separate 2620 * via this class so that the two FindListeners can potentially exist at once. 2621 */ 2622 private class FindListenerDistributor implements FindListener { 2623 private FindListener mFindDialogFindListener; 2624 private FindListener mUserFindListener; 2625 2626 @Override 2627 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, 2628 boolean isDoneCounting) { 2629 if (mFindDialogFindListener != null) { 2630 mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2631 isDoneCounting); 2632 } 2633 2634 if (mUserFindListener != null) { 2635 mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, 2636 isDoneCounting); 2637 } 2638 } 2639 } 2640 private FindListenerDistributor mFindListener; 2641 2642 private void setupFindListenerIfNeeded() { 2643 if (mFindListener == null) { 2644 mFindListener = new FindListenerDistributor(); 2645 mProvider.setFindListener(mFindListener); 2646 } 2647 } 2648 2649 private void ensureProviderCreated() { 2650 checkThread(); 2651 if (mProvider == null) { 2652 // As this can get called during the base class constructor chain, pass the minimum 2653 // number of dependencies here; the rest are deferred to init(). 2654 mProvider = getFactory().createWebView(this, new PrivateAccess()); 2655 } 2656 } 2657 2658 private static WebViewFactoryProvider getFactory() { 2659 return WebViewFactory.getProvider(); 2660 } 2661 2662 private final Looper mWebViewThread = Looper.myLooper(); 2663 2664 private void checkThread() { 2665 // Ignore mWebViewThread == null because this can be called during in the super class 2666 // constructor, before this class's own constructor has even started. 2667 if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) { 2668 Throwable throwable = new Throwable( 2669 "A WebView method was called on thread '" + 2670 Thread.currentThread().getName() + "'. " + 2671 "All WebView methods must be called on the same thread. " + 2672 "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() + 2673 ", FYI main Looper is " + Looper.getMainLooper() + ")"); 2674 Log.w(LOGTAG, Log.getStackTraceString(throwable)); 2675 StrictMode.onWebViewMethodCalledOnWrongThread(throwable); 2676 2677 if (sEnforceThreadChecking) { 2678 throw new RuntimeException(throwable); 2679 } 2680 } 2681 } 2682 2683 //------------------------------------------------------------------------- 2684 // Override View methods 2685 //------------------------------------------------------------------------- 2686 2687 // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures 2688 // there's a corresponding override (or better, caller) for each of them in here. 2689 2690 @Override 2691 protected void onAttachedToWindow() { 2692 super.onAttachedToWindow(); 2693 mProvider.getViewDelegate().onAttachedToWindow(); 2694 } 2695 2696 /** @hide */ 2697 @Override 2698 protected void onDetachedFromWindowInternal() { 2699 mProvider.getViewDelegate().onDetachedFromWindow(); 2700 super.onDetachedFromWindowInternal(); 2701 } 2702 2703 /** @hide */ 2704 @Override 2705 public void onMovedToDisplay(int displayId, Configuration config) { 2706 mProvider.getViewDelegate().onMovedToDisplay(displayId, config); 2707 } 2708 2709 @Override 2710 public void setLayoutParams(ViewGroup.LayoutParams params) { 2711 mProvider.getViewDelegate().setLayoutParams(params); 2712 } 2713 2714 @Override 2715 public void setOverScrollMode(int mode) { 2716 super.setOverScrollMode(mode); 2717 // This method may be called in the constructor chain, before the WebView provider is 2718 // created. 2719 ensureProviderCreated(); 2720 mProvider.getViewDelegate().setOverScrollMode(mode); 2721 } 2722 2723 @Override 2724 public void setScrollBarStyle(int style) { 2725 mProvider.getViewDelegate().setScrollBarStyle(style); 2726 super.setScrollBarStyle(style); 2727 } 2728 2729 @Override 2730 protected int computeHorizontalScrollRange() { 2731 return mProvider.getScrollDelegate().computeHorizontalScrollRange(); 2732 } 2733 2734 @Override 2735 protected int computeHorizontalScrollOffset() { 2736 return mProvider.getScrollDelegate().computeHorizontalScrollOffset(); 2737 } 2738 2739 @Override 2740 protected int computeVerticalScrollRange() { 2741 return mProvider.getScrollDelegate().computeVerticalScrollRange(); 2742 } 2743 2744 @Override 2745 protected int computeVerticalScrollOffset() { 2746 return mProvider.getScrollDelegate().computeVerticalScrollOffset(); 2747 } 2748 2749 @Override 2750 protected int computeVerticalScrollExtent() { 2751 return mProvider.getScrollDelegate().computeVerticalScrollExtent(); 2752 } 2753 2754 @Override 2755 public void computeScroll() { 2756 mProvider.getScrollDelegate().computeScroll(); 2757 } 2758 2759 @Override 2760 public boolean onHoverEvent(MotionEvent event) { 2761 return mProvider.getViewDelegate().onHoverEvent(event); 2762 } 2763 2764 @Override 2765 public boolean onTouchEvent(MotionEvent event) { 2766 return mProvider.getViewDelegate().onTouchEvent(event); 2767 } 2768 2769 @Override 2770 public boolean onGenericMotionEvent(MotionEvent event) { 2771 return mProvider.getViewDelegate().onGenericMotionEvent(event); 2772 } 2773 2774 @Override 2775 public boolean onTrackballEvent(MotionEvent event) { 2776 return mProvider.getViewDelegate().onTrackballEvent(event); 2777 } 2778 2779 @Override 2780 public boolean onKeyDown(int keyCode, KeyEvent event) { 2781 return mProvider.getViewDelegate().onKeyDown(keyCode, event); 2782 } 2783 2784 @Override 2785 public boolean onKeyUp(int keyCode, KeyEvent event) { 2786 return mProvider.getViewDelegate().onKeyUp(keyCode, event); 2787 } 2788 2789 @Override 2790 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 2791 return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event); 2792 } 2793 2794 /* 2795 TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not 2796 to be delegating them too. 2797 2798 @Override 2799 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 2800 return mProvider.getViewDelegate().onKeyPreIme(keyCode, event); 2801 } 2802 @Override 2803 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 2804 return mProvider.getViewDelegate().onKeyLongPress(keyCode, event); 2805 } 2806 @Override 2807 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 2808 return mProvider.getViewDelegate().onKeyShortcut(keyCode, event); 2809 } 2810 */ 2811 2812 @Override 2813 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 2814 AccessibilityNodeProvider provider = 2815 mProvider.getViewDelegate().getAccessibilityNodeProvider(); 2816 return provider == null ? super.getAccessibilityNodeProvider() : provider; 2817 } 2818 2819 @Deprecated 2820 @Override 2821 public boolean shouldDelayChildPressedState() { 2822 return mProvider.getViewDelegate().shouldDelayChildPressedState(); 2823 } 2824 2825 @Override 2826 public CharSequence getAccessibilityClassName() { 2827 return WebView.class.getName(); 2828 } 2829 2830 @Override 2831 public void onProvideVirtualStructure(ViewStructure structure) { 2832 mProvider.getViewDelegate().onProvideVirtualStructure(structure); 2833 } 2834 2835 /** 2836 * {@inheritDoc} 2837 * 2838 * <p>The {@link ViewStructure} traditionally represents a {@link View}, while for web pages 2839 * it represent HTML nodes. Hence, it's necessary to "map" the HTML properties in a way that is 2840 * understood by the {@link android.service.autofill.AutofillService} implementations: 2841 * 2842 * <ol> 2843 * <li>Only the HTML nodes inside a {@code FORM} are generated. 2844 * <li>The source of the HTML is set using {@link ViewStructure#setWebDomain(String)} in the 2845 * node representing the WebView. 2846 * <li>If a web page has multiple {@code FORM}s, only the data for the current form is 2847 * represented—if the user taps a field from another form, then the current autofill 2848 * context is canceled (by calling {@link android.view.autofill.AutofillManager#cancel()} and 2849 * a new context is created for that {@code FORM}. 2850 * <li>Similarly, if the page has {@code IFRAME} nodes, they are not initially represented in 2851 * the view structure until the user taps a field from a {@code FORM} inside the 2852 * {@code IFRAME}, in which case it would be treated the same way as multiple forms described 2853 * above, except that the {@link ViewStructure#setWebDomain(String) web domain} of the 2854 * {@code FORM} contains the {@code src} attribute from the {@code IFRAME} node. 2855 * <li>The W3C autofill field ({@code autocomplete} tag attribute) maps to 2856 * {@link ViewStructure#setAutofillHints(String[])}. 2857 * <li>If the view is editable, the {@link ViewStructure#setAutofillType(int)} and 2858 * {@link ViewStructure#setAutofillValue(AutofillValue)} must be set. 2859 * <li>The {@code placeholder} attribute maps to {@link ViewStructure#setHint(CharSequence)}. 2860 * <li>Other HTML attributes can be represented through 2861 * {@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}. 2862 * </ol> 2863 * 2864 * <p>If the WebView implementation can determine that the value of a field was set statically 2865 * (for example, not through Javascript), it should also call 2866 * {@code structure.setDataIsSensitive(false)}. 2867 * 2868 * <p>For example, an HTML form with 2 fields for username and password: 2869 * 2870 * <pre class="prettyprint"> 2871 * <label>Username:</label> 2872 * <input type="text" name="username" id="user" value="Type your username" autocomplete="username" placeholder="Email or username"> 2873 * <label>Password:</label> 2874 * <input type="password" name="password" id="pass" autocomplete="current-password" placeholder="Password"> 2875 * </pre> 2876 * 2877 * <p>Would map to: 2878 * 2879 * <pre class="prettyprint"> 2880 * int index = structure.addChildCount(2); 2881 * ViewStructure username = structure.newChild(index); 2882 * username.setAutofillId(structure.getAutofillId(), 1); // id 1 - first child 2883 * username.setAutofillHints("username"); 2884 * username.setHtmlInfo(username.newHtmlInfoBuilder("input") 2885 * .addAttribute("type", "text") 2886 * .addAttribute("name", "username") 2887 * .addAttribute("label", "Username:") 2888 * .build()); 2889 * username.setHint("Email or username"); 2890 * username.setAutofillType(View.AUTOFILL_TYPE_TEXT); 2891 * username.setAutofillValue(AutofillValue.forText("Type your username")); 2892 * // Value of the field is not sensitive because it was created statically and not changed. 2893 * username.setDataIsSensitive(false); 2894 * 2895 * ViewStructure password = structure.newChild(index + 1); 2896 * username.setAutofillId(structure, 2); // id 2 - second child 2897 * password.setAutofillHints("current-password"); 2898 * password.setHtmlInfo(password.newHtmlInfoBuilder("input") 2899 * .addAttribute("type", "password") 2900 * .addAttribute("name", "password") 2901 * .addAttribute("label", "Password:") 2902 * .build()); 2903 * password.setHint("Password"); 2904 * password.setAutofillType(View.AUTOFILL_TYPE_TEXT); 2905 * </pre> 2906 */ 2907 @Override 2908 public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { 2909 mProvider.getViewDelegate().onProvideAutofillVirtualStructure(structure, flags); 2910 } 2911 2912 @Override 2913 public void autofill(SparseArray<AutofillValue>values) { 2914 mProvider.getViewDelegate().autofill(values); 2915 } 2916 2917 @Override 2918 public boolean isVisibleToUserForAutofill(int virtualId) { 2919 return mProvider.getViewDelegate().isVisibleToUserForAutofill(virtualId); 2920 } 2921 2922 /** @hide */ 2923 @Override 2924 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 2925 super.onInitializeAccessibilityNodeInfoInternal(info); 2926 mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info); 2927 } 2928 2929 /** @hide */ 2930 @Override 2931 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 2932 super.onInitializeAccessibilityEventInternal(event); 2933 mProvider.getViewDelegate().onInitializeAccessibilityEvent(event); 2934 } 2935 2936 /** @hide */ 2937 @Override 2938 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 2939 return mProvider.getViewDelegate().performAccessibilityAction(action, arguments); 2940 } 2941 2942 /** @hide */ 2943 @Override 2944 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 2945 int l, int t, int r, int b) { 2946 mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 2947 } 2948 2949 @Override 2950 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { 2951 mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY); 2952 } 2953 2954 @Override 2955 protected void onWindowVisibilityChanged(int visibility) { 2956 super.onWindowVisibilityChanged(visibility); 2957 mProvider.getViewDelegate().onWindowVisibilityChanged(visibility); 2958 } 2959 2960 @Override 2961 protected void onDraw(Canvas canvas) { 2962 mProvider.getViewDelegate().onDraw(canvas); 2963 } 2964 2965 @Override 2966 public boolean performLongClick() { 2967 return mProvider.getViewDelegate().performLongClick(); 2968 } 2969 2970 @Override 2971 protected void onConfigurationChanged(Configuration newConfig) { 2972 mProvider.getViewDelegate().onConfigurationChanged(newConfig); 2973 } 2974 2975 /** 2976 * Creates a new InputConnection for an InputMethod to interact with the WebView. 2977 * This is similar to {@link View#onCreateInputConnection} but note that WebView 2978 * calls InputConnection methods on a thread other than the UI thread. 2979 * If these methods are overridden, then the overriding methods should respect 2980 * thread restrictions when calling View methods or accessing data. 2981 */ 2982 @Override 2983 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 2984 return mProvider.getViewDelegate().onCreateInputConnection(outAttrs); 2985 } 2986 2987 @Override 2988 public boolean onDragEvent(DragEvent event) { 2989 return mProvider.getViewDelegate().onDragEvent(event); 2990 } 2991 2992 @Override 2993 protected void onVisibilityChanged(View changedView, int visibility) { 2994 super.onVisibilityChanged(changedView, visibility); 2995 // This method may be called in the constructor chain, before the WebView provider is 2996 // created. 2997 ensureProviderCreated(); 2998 mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility); 2999 } 3000 3001 @Override 3002 public void onWindowFocusChanged(boolean hasWindowFocus) { 3003 mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus); 3004 super.onWindowFocusChanged(hasWindowFocus); 3005 } 3006 3007 @Override 3008 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 3009 mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect); 3010 super.onFocusChanged(focused, direction, previouslyFocusedRect); 3011 } 3012 3013 /** @hide */ 3014 @Override 3015 protected boolean setFrame(int left, int top, int right, int bottom) { 3016 return mProvider.getViewDelegate().setFrame(left, top, right, bottom); 3017 } 3018 3019 @Override 3020 protected void onSizeChanged(int w, int h, int ow, int oh) { 3021 super.onSizeChanged(w, h, ow, oh); 3022 mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh); 3023 } 3024 3025 @Override 3026 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 3027 super.onScrollChanged(l, t, oldl, oldt); 3028 mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt); 3029 } 3030 3031 @Override 3032 public boolean dispatchKeyEvent(KeyEvent event) { 3033 return mProvider.getViewDelegate().dispatchKeyEvent(event); 3034 } 3035 3036 @Override 3037 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 3038 return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect); 3039 } 3040 3041 @Override 3042 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 3043 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 3044 mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec); 3045 } 3046 3047 @Override 3048 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 3049 return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate); 3050 } 3051 3052 @Override 3053 public void setBackgroundColor(int color) { 3054 mProvider.getViewDelegate().setBackgroundColor(color); 3055 } 3056 3057 @Override 3058 public void setLayerType(int layerType, Paint paint) { 3059 super.setLayerType(layerType, paint); 3060 mProvider.getViewDelegate().setLayerType(layerType, paint); 3061 } 3062 3063 @Override 3064 protected void dispatchDraw(Canvas canvas) { 3065 mProvider.getViewDelegate().preDispatchDraw(canvas); 3066 super.dispatchDraw(canvas); 3067 } 3068 3069 @Override 3070 public void onStartTemporaryDetach() { 3071 super.onStartTemporaryDetach(); 3072 mProvider.getViewDelegate().onStartTemporaryDetach(); 3073 } 3074 3075 @Override 3076 public void onFinishTemporaryDetach() { 3077 super.onFinishTemporaryDetach(); 3078 mProvider.getViewDelegate().onFinishTemporaryDetach(); 3079 } 3080 3081 @Override 3082 public Handler getHandler() { 3083 return mProvider.getViewDelegate().getHandler(super.getHandler()); 3084 } 3085 3086 @Override 3087 public View findFocus() { 3088 return mProvider.getViewDelegate().findFocus(super.findFocus()); 3089 } 3090 3091 /** 3092 * If WebView has already been loaded into the current process this method will return the 3093 * package that was used to load it. Otherwise, the package that would be used if the WebView 3094 * was loaded right now will be returned; this does not cause WebView to be loaded, so this 3095 * information may become outdated at any time. 3096 * The WebView package changes either when the current WebView package is updated, disabled, or 3097 * uninstalled. It can also be changed through a Developer Setting. 3098 * If the WebView package changes, any app process that has loaded WebView will be killed. The 3099 * next time the app starts and loads WebView it will use the new WebView package instead. 3100 * @return the current WebView package, or {@code null} if there is none. 3101 */ 3102 @Nullable 3103 public static PackageInfo getCurrentWebViewPackage() { 3104 PackageInfo webviewPackage = WebViewFactory.getLoadedPackageInfo(); 3105 if (webviewPackage != null) { 3106 return webviewPackage; 3107 } 3108 3109 IWebViewUpdateService service = WebViewFactory.getUpdateService(); 3110 if (service == null) { 3111 return null; 3112 } 3113 try { 3114 return service.getCurrentWebViewPackage(); 3115 } catch (RemoteException e) { 3116 throw e.rethrowFromSystemServer(); 3117 } 3118 } 3119 3120 /** 3121 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 3122 * 3123 * @param requestCode The integer request code originally supplied to 3124 * startActivityForResult(), allowing you to identify who this 3125 * result came from. 3126 * @param resultCode The integer result code returned by the child activity 3127 * through its setResult(). 3128 * @param data An Intent, which can return result data to the caller 3129 * (various data can be attached to Intent "extras"). 3130 * @hide 3131 */ 3132 @Override 3133 public void onActivityResult(int requestCode, int resultCode, Intent data) { 3134 mProvider.getViewDelegate().onActivityResult(requestCode, resultCode, data); 3135 } 3136 3137 @Override 3138 public boolean onCheckIsTextEditor() { 3139 return mProvider.getViewDelegate().onCheckIsTextEditor(); 3140 } 3141 3142 /** @hide */ 3143 @Override 3144 protected void encodeProperties(@NonNull ViewHierarchyEncoder encoder) { 3145 super.encodeProperties(encoder); 3146 3147 checkThread(); 3148 encoder.addProperty("webview:contentHeight", mProvider.getContentHeight()); 3149 encoder.addProperty("webview:contentWidth", mProvider.getContentWidth()); 3150 encoder.addProperty("webview:scale", mProvider.getScale()); 3151 encoder.addProperty("webview:title", mProvider.getTitle()); 3152 encoder.addProperty("webview:url", mProvider.getUrl()); 3153 encoder.addProperty("webview:originalUrl", mProvider.getOriginalUrl()); 3154 } 3155} 3156