WebView.java revision abeb6a791501151308d06db6aebb438e16c1a784
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.Widget; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.graphics.Bitmap; 23import android.graphics.Canvas; 24import android.graphics.Picture; 25import android.graphics.Rect; 26import android.graphics.drawable.Drawable; 27import android.net.http.SslCertificate; 28import android.os.Bundle; 29import android.os.Looper; 30import android.os.Message; 31import android.os.StrictMode; 32import android.util.AttributeSet; 33import android.util.Log; 34import android.view.KeyEvent; 35import android.view.MotionEvent; 36import android.view.View; 37import android.view.ViewGroup; 38import android.view.ViewGroup.LayoutParams; 39import android.view.ViewTreeObserver; 40import android.view.accessibility.AccessibilityEvent; 41import android.view.accessibility.AccessibilityNodeInfo; 42import android.view.inputmethod.EditorInfo; 43import android.view.inputmethod.InputConnection; 44import android.widget.AbsoluteLayout; 45 46import java.io.File; 47import java.util.Map; 48 49/** 50 * <p>A View that displays web pages. This class is the basis upon which you 51 * can roll your own web browser or simply display some online content within your Activity. 52 * It uses the WebKit rendering engine to display 53 * web pages and includes methods to navigate forward and backward 54 * through a history, zoom in and out, perform text searches and more.</p> 55 * <p>To enable the built-in zoom, set 56 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 57 * (introduced in API version 3). 58 * <p>Note that, in order for your Activity to access the Internet and load web pages 59 * in a WebView, you must add the {@code INTERNET} permissions to your 60 * Android Manifest file:</p> 61 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 62 * 63 * <p>This must be a child of the <a 64 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a> 65 * element.</p> 66 * 67 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View 68 * tutorial</a>.</p> 69 * 70 * <h3>Basic usage</h3> 71 * 72 * <p>By default, a WebView provides no browser-like widgets, does not 73 * enable JavaScript and web page errors are ignored. If your goal is only 74 * to display some HTML as a part of your UI, this is probably fine; 75 * the user won't need to interact with the web page beyond reading 76 * it, and the web page won't need to interact with the user. If you 77 * actually want a full-blown web browser, then you probably want to 78 * invoke the Browser application with a URL Intent rather than show it 79 * with a WebView. For example: 80 * <pre> 81 * Uri uri = Uri.parse("http://www.example.com"); 82 * Intent intent = new Intent(Intent.ACTION_VIEW, uri); 83 * startActivity(intent); 84 * </pre> 85 * <p>See {@link android.content.Intent} for more information.</p> 86 * 87 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout, 88 * or set the entire Activity window as a WebView during {@link 89 * android.app.Activity#onCreate(Bundle) onCreate()}:</p> 90 * <pre class="prettyprint"> 91 * WebView webview = new WebView(this); 92 * setContentView(webview); 93 * </pre> 94 * 95 * <p>Then load the desired web page:</p> 96 * <pre> 97 * // Simplest usage: note that an exception will NOT be thrown 98 * // if there is an error loading this page (see below). 99 * webview.loadUrl("http://slashdot.org/"); 100 * 101 * // OR, you can also load from an HTML string: 102 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 103 * webview.loadData(summary, "text/html", null); 104 * // ... although note that there are restrictions on what this HTML can do. 105 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link 106 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info. 107 * </pre> 108 * 109 * <p>A WebView has several customization points where you can add your 110 * own behavior. These are:</p> 111 * 112 * <ul> 113 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 114 * This class is called when something that might impact a 115 * browser UI happens, for instance, progress updates and 116 * JavaScript alerts are sent here (see <a 117 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>). 118 * </li> 119 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 120 * It will be called when things happen that impact the 121 * rendering of the content, eg, errors or form submissions. You 122 * can also intercept URL loading here (via {@link 123 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String) 124 * shouldOverrideUrlLoading()}).</li> 125 * <li>Modifying the {@link android.webkit.WebSettings}, such as 126 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean) 127 * setJavaScriptEnabled()}. </li> 128 * <li>Injecting Java objects into the WebView using the 129 * {@link android.webkit.WebView#addJavascriptInterface} method. This 130 * method allows you to inject Java objects into a page's JavaScript 131 * context, so that they can be accessed by JavaScript in the page.</li> 132 * </ul> 133 * 134 * <p>Here's a more complicated example, showing error handling, 135 * settings, and progress notification:</p> 136 * 137 * <pre class="prettyprint"> 138 * // Let's display the progress in the activity title bar, like the 139 * // browser app does. 140 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 141 * 142 * webview.getSettings().setJavaScriptEnabled(true); 143 * 144 * final Activity activity = this; 145 * webview.setWebChromeClient(new WebChromeClient() { 146 * public void onProgressChanged(WebView view, int progress) { 147 * // Activities and WebViews measure progress with different scales. 148 * // The progress meter will automatically disappear when we reach 100% 149 * activity.setProgress(progress * 1000); 150 * } 151 * }); 152 * webview.setWebViewClient(new WebViewClient() { 153 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 154 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 155 * } 156 * }); 157 * 158 * webview.loadUrl("http://slashdot.org/"); 159 * </pre> 160 * 161 * <h3>Cookie and window management</h3> 162 * 163 * <p>For obvious security reasons, your application has its own 164 * cache, cookie store etc.—it does not share the Browser 165 * application's data. Cookies are managed on a separate thread, so 166 * operations like index building don't block the UI 167 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 168 * if you want to use cookies in your application. 169 * </p> 170 * 171 * <p>By default, requests by the HTML to open new windows are 172 * ignored. This is true whether they be opened by JavaScript or by 173 * the target attribute on a link. You can customize your 174 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows, 175 * and render them in whatever manner you want.</p> 176 * 177 * <p>The standard behavior for an Activity is to be destroyed and 178 * recreated when the device orientation or any other configuration changes. This will cause 179 * the WebView to reload the current page. If you don't want that, you 180 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} 181 * changes, and then just leave the WebView alone. It'll automatically 182 * re-orient itself as appropriate. Read <a 183 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for 184 * more information about how to handle configuration changes during runtime.</p> 185 * 186 * 187 * <h3>Building web pages to support different screen densities</h3> 188 * 189 * <p>The screen density of a device is based on the screen resolution. A screen with low density 190 * has fewer available pixels per inch, where a screen with high density 191 * has more — sometimes significantly more — pixels per inch. The density of a 192 * screen is important because, other things being equal, a UI element (such as a button) whose 193 * height and width are defined in terms of screen pixels will appear larger on the lower density 194 * screen and smaller on the higher density screen. 195 * For simplicity, Android collapses all actual screen densities into three generalized densities: 196 * high, medium, and low.</p> 197 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default 198 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen 199 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels 200 * are bigger). 201 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help 202 * you (as a web developer) target screens with different screen densities.</p> 203 * <p>Here's a summary of the features you can use to handle different screen densities:</p> 204 * <ul> 205 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the 206 * default scaling factor used for the current device. For example, if the value of {@code 207 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device 208 * and default scaling is not applied to the web page; if the value is "1.5", then the device is 209 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the 210 * value is "0.75", then the device is considered a low density device (ldpi) and the content is 211 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property 212 * (discussed below), then you can stop this default scaling behavior.</li> 213 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen 214 * densities for which this style sheet is to be used. The corresponding value should be either 215 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium 216 * density, or high density screens, respectively. For example: 217 * <pre> 218 * <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /></pre> 219 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5, 220 * which is the high density pixel ratio.</p> 221 * </li> 222 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use 223 * this to specify the target density for which the web page is designed, using the following 224 * values: 225 * <ul> 226 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never 227 * occurs.</li> 228 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down 229 * as appropriate.</li> 230 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and 231 * low density screens scale down. This is also the default behavior.</li> 232 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up 233 * as appropriate.</li> 234 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted 235 * values are 70-400).</li> 236 * </ul> 237 * <p>Here's an example meta tag to specify the target density:</p> 238 * <pre><meta name="viewport" content="target-densitydpi=device-dpi" /></pre></li> 239 * </ul> 240 * <p>If you want to modify your web page for different densities, by using the {@code 241 * -webkit-device-pixel-ratio} CSS media query and/or the {@code 242 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta 243 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and 244 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p> 245 * 246 * <h3>HTML5 Video support</h3> 247 * 248 * <p>In order to support inline HTML5 video in your application, you need to have hardware 249 * acceleration turned on, and set a {@link android.webkit.WebChromeClient}. For full screen support, 250 * implementations of {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)} 251 * and {@link WebChromeClient#onHideCustomView()} are required, 252 * {@link WebChromeClient#getVideoLoadingProgressView()} is optional. 253 * </p> 254 * 255 * 256 */ 257/* 258 * Implementation notes. 259 * The WebView is a thin API class that delegates its public API to a backend WebViewProvider 260 * class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons. 261 * Methods are delegated to the provider implementation: all public API methods introduced in this 262 * file are fully delegated, whereas public and protected methods from the View base classes are 263 * only delegated where a specific need exists for them to do so. 264 */ 265@Widget 266public class WebView extends AbsoluteLayout 267 implements ViewTreeObserver.OnGlobalFocusChangeListener, 268 ViewGroup.OnHierarchyChangeListener { 269 270 // Default Provider factory class name. 271 private static final String DEFAULT_WEB_VIEW_FACTORY = "android.webkit.WebViewClassic$Factory"; 272 273 private static final String LOGTAG = "webview_proxy"; 274 // TODO: flip DEBUG to always be disabled. 275 private static final boolean DEBUG = true; 276 277 /** 278 * Transportation object for returning WebView across thread boundaries. 279 */ 280 public class WebViewTransport { 281 private WebView mWebview; 282 283 /** 284 * Set the WebView to the transportation object. 285 * @param webview The WebView to transport. 286 */ 287 public synchronized void setWebView(WebView webview) { 288 mWebview = webview; 289 } 290 291 /** 292 * Return the WebView object. 293 * @return WebView The transported WebView object. 294 */ 295 public synchronized WebView getWebView() { 296 return mWebview; 297 } 298 } 299 300 /** 301 * URI scheme for telephone number 302 */ 303 public static final String SCHEME_TEL = "tel:"; 304 /** 305 * URI scheme for email address 306 */ 307 public static final String SCHEME_MAILTO = "mailto:"; 308 /** 309 * URI scheme for map address 310 */ 311 public static final String SCHEME_GEO = "geo:0,0?q="; 312 313 /** 314 * Interface to listen for new pictures as they change. 315 * @deprecated This interface is now obsolete. 316 */ 317 @Deprecated 318 public interface PictureListener { 319 /** 320 * Notify the listener that the picture has changed. 321 * @param view The WebView that owns the picture. 322 * @param picture The new picture. 323 * @deprecated Due to internal changes, the picture does not include 324 * composited layers such as fixed position elements or scrollable divs. 325 * While the PictureListener API can still be used to detect changes in 326 * the WebView content, you are advised against its usage until a replacement 327 * is provided in a future Android release 328 */ 329 @Deprecated 330 public void onNewPicture(WebView view, Picture picture); 331 } 332 333 public static class HitTestResult { 334 /** 335 * Default HitTestResult, where the target is unknown 336 */ 337 public static final int UNKNOWN_TYPE = 0; 338 /** 339 * @deprecated This type is no longer used. 340 */ 341 @Deprecated 342 public static final int ANCHOR_TYPE = 1; 343 /** 344 * HitTestResult for hitting a phone number 345 */ 346 public static final int PHONE_TYPE = 2; 347 /** 348 * HitTestResult for hitting a map address 349 */ 350 public static final int GEO_TYPE = 3; 351 /** 352 * HitTestResult for hitting an email address 353 */ 354 public static final int EMAIL_TYPE = 4; 355 /** 356 * HitTestResult for hitting an HTML::img tag 357 */ 358 public static final int IMAGE_TYPE = 5; 359 /** 360 * @deprecated This type is no longer used. 361 */ 362 @Deprecated 363 public static final int IMAGE_ANCHOR_TYPE = 6; 364 /** 365 * HitTestResult for hitting a HTML::a tag with src=http 366 */ 367 public static final int SRC_ANCHOR_TYPE = 7; 368 /** 369 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 370 */ 371 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 372 /** 373 * HitTestResult for hitting an edit text area 374 */ 375 public static final int EDIT_TEXT_TYPE = 9; 376 377 private int mType; 378 private String mExtra; 379 380 /** 381 * @hide Only for use by WebViewProvider implementations 382 */ 383 public HitTestResult() { 384 mType = UNKNOWN_TYPE; 385 } 386 387 /** 388 * @hide Only for use by WebViewProvider implementations 389 */ 390 public void setType(int type) { 391 mType = type; 392 } 393 394 /** 395 * @hide Only for use by WebViewProvider implementations 396 */ 397 public void setExtra(String extra) { 398 mExtra = extra; 399 } 400 401 /** 402 * Gets the type of the hit test result. 403 * @return See the XXX_TYPE constants defined in this class. 404 */ 405 public int getType() { 406 return mType; 407 } 408 409 /** 410 * Gets additional type-dependant information about the result, see 411 * {@link WebView#getHitTestResult()} for details. 412 * @return may either be null or contain extra information about this result. 413 */ 414 public String getExtra() { 415 return mExtra; 416 } 417 } 418 419 /** 420 * Construct a new WebView with a Context object. 421 * @param context A Context object used to access application assets. 422 */ 423 public WebView(Context context) { 424 this(context, null); 425 } 426 427 /** 428 * Construct a new WebView with layout parameters. 429 * @param context A Context object used to access application assets. 430 * @param attrs An AttributeSet passed to our parent. 431 */ 432 public WebView(Context context, AttributeSet attrs) { 433 this(context, attrs, com.android.internal.R.attr.webViewStyle); 434 } 435 436 /** 437 * Construct a new WebView with layout parameters and a default style. 438 * @param context A Context object used to access application assets. 439 * @param attrs An AttributeSet passed to our parent. 440 * @param defStyle The default style resource ID. 441 */ 442 public WebView(Context context, AttributeSet attrs, int defStyle) { 443 this(context, attrs, defStyle, false); 444 } 445 446 /** 447 * Construct a new WebView with layout parameters and a default style. 448 * @param context A Context object used to access application assets. 449 * @param attrs An AttributeSet passed to our parent. 450 * @param defStyle The default style resource ID. 451 * @param privateBrowsing If true the web view will be initialized in private mode. 452 */ 453 public WebView(Context context, AttributeSet attrs, int defStyle, 454 boolean privateBrowsing) { 455 this(context, attrs, defStyle, null, privateBrowsing); 456 } 457 458 /** 459 * Construct a new WebView with layout parameters, a default style and a set 460 * of custom Javscript interfaces to be added to the WebView at initialization 461 * time. This guarantees that these interfaces will be available when the JS 462 * context is initialized. 463 * @param context A Context object used to access application assets. 464 * @param attrs An AttributeSet passed to our parent. 465 * @param defStyle The default style resource ID. 466 * @param javaScriptInterfaces is a Map of interface names, as keys, and 467 * object implementing those interfaces, as values. 468 * @param privateBrowsing If true the web view will be initialized in private mode. 469 * @hide This is used internally by dumprendertree, as it requires the javaScript interfaces to 470 * be added synchronously, before a subsequent loadUrl call takes effect. 471 */ 472 @SuppressWarnings("deprecation") // for super() call into deprecated base class constructor. 473 protected WebView(Context context, AttributeSet attrs, int defStyle, 474 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 475 super(context, attrs, defStyle); 476 if (context == null) { 477 throw new IllegalArgumentException("Invalid context argument"); 478 } 479 checkThread(); 480 481 ensureProviderCreated(); 482 mProvider.init(javaScriptInterfaces, privateBrowsing); 483 } 484 485 /** 486 * Specify whether the horizontal scrollbar has overlay style. 487 * @param overlay TRUE if horizontal scrollbar should have overlay style. 488 */ 489 public void setHorizontalScrollbarOverlay(boolean overlay) { 490 checkThread(); 491 mProvider.setHorizontalScrollbarOverlay(overlay); 492 } 493 494 /** 495 * Specify whether the vertical scrollbar has overlay style. 496 * @param overlay TRUE if vertical scrollbar should have overlay style. 497 */ 498 public void setVerticalScrollbarOverlay(boolean overlay) { 499 checkThread(); 500 mProvider.setVerticalScrollbarOverlay(overlay); 501 } 502 503 /** 504 * Return whether horizontal scrollbar has overlay style 505 * @return TRUE if horizontal scrollbar has overlay style. 506 */ 507 public boolean overlayHorizontalScrollbar() { 508 checkThread(); 509 return mProvider.overlayHorizontalScrollbar(); 510 } 511 512 /** 513 * Return whether vertical scrollbar has overlay style 514 * @return TRUE if vertical scrollbar has overlay style. 515 */ 516 public boolean overlayVerticalScrollbar() { 517 checkThread(); 518 return mProvider.overlayVerticalScrollbar(); 519 } 520 521 /** 522 * Return the visible height (in pixels) of the embedded title bar (if any). 523 * 524 * @deprecated This method is now obsolete. 525 */ 526 public int getVisibleTitleHeight() { 527 checkThread(); 528 return mProvider.getVisibleTitleHeight(); 529 } 530 531 /** 532 * @return The SSL certificate for the main top-level page or null if 533 * there is no certificate (the site is not secure). 534 */ 535 public SslCertificate getCertificate() { 536 checkThread(); 537 return mProvider.getCertificate(); 538 } 539 540 /** 541 * Sets the SSL certificate for the main top-level page. 542 */ 543 public void setCertificate(SslCertificate certificate) { 544 checkThread(); 545 mProvider.setCertificate(certificate); 546 } 547 548 //------------------------------------------------------------------------- 549 // Methods called by activity 550 //------------------------------------------------------------------------- 551 552 /** 553 * Save the username and password for a particular host in the WebView's 554 * internal database. 555 * @param host The host that required the credentials. 556 * @param username The username for the given host. 557 * @param password The password for the given host. 558 */ 559 public void savePassword(String host, String username, String password) { 560 checkThread(); 561 mProvider.savePassword(host, username, password); 562 } 563 564 /** 565 * Set the HTTP authentication credentials for a given host and realm. 566 * 567 * @param host The host for the credentials. 568 * @param realm The realm for the credentials. 569 * @param username The username for the password. If it is null, it means 570 * password can't be saved. 571 * @param password The password 572 */ 573 public void setHttpAuthUsernamePassword(String host, String realm, 574 String username, String password) { 575 checkThread(); 576 mProvider.setHttpAuthUsernamePassword(host, realm, username, password); 577 } 578 579 /** 580 * Retrieve the HTTP authentication username and password for a given 581 * host & realm pair 582 * 583 * @param host The host for which the credentials apply. 584 * @param realm The realm for which the credentials apply. 585 * @return String[] if found, String[0] is username, which can be null and 586 * String[1] is password. Return null if it can't find anything. 587 */ 588 public String[] getHttpAuthUsernamePassword(String host, String realm) { 589 checkThread(); 590 return mProvider.getHttpAuthUsernamePassword(host, realm); 591 } 592 593 /** 594 * Destroy the internal state of the WebView. This method should be called 595 * after the WebView has been removed from the view system. No other 596 * methods may be called on a WebView after destroy. 597 */ 598 public void destroy() { 599 checkThread(); 600 mProvider.destroy(); 601 } 602 603 /** 604 * Enables platform notifications of data state and proxy changes. 605 * Notifications are enabled by default. 606 * 607 * @deprecated This method is now obsolete. 608 */ 609 @Deprecated 610 public static void enablePlatformNotifications() { 611 checkThread(); 612 getFactory().getStatics().setPlatformNotificationsEnabled(true); 613 } 614 615 /** 616 * Disables platform notifications of data state and proxy changes. 617 * Notifications are enabled by default. 618 * 619 * @deprecated This method is now obsolete. 620 */ 621 @Deprecated 622 public static void disablePlatformNotifications() { 623 checkThread(); 624 getFactory().getStatics().setPlatformNotificationsEnabled(false); 625 } 626 627 /** 628 * Inform WebView of the network state. This is used to set 629 * the JavaScript property window.navigator.isOnline and 630 * generates the online/offline event as specified in HTML5, sec. 5.7.7 631 * @param networkUp boolean indicating if network is available 632 */ 633 public void setNetworkAvailable(boolean networkUp) { 634 checkThread(); 635 mProvider.setNetworkAvailable(networkUp); 636 } 637 638 /** 639 * Save the state of this WebView used in 640 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 641 * method no longer stores the display data for this WebView. The previous 642 * behavior could potentially leak files if {@link #restoreState} was never 643 * called. See {@link #savePicture} and {@link #restorePicture} for saving 644 * and restoring the display data. 645 * @param outState The Bundle to store the WebView state. 646 * @return The same copy of the back/forward list used to save the state. If 647 * saveState fails, the returned list will be null. 648 * @see #savePicture 649 * @see #restorePicture 650 */ 651 public WebBackForwardList saveState(Bundle outState) { 652 checkThread(); 653 return mProvider.saveState(outState); 654 } 655 656 /** 657 * Save the current display data to the Bundle given. Used in conjunction 658 * with {@link #saveState}. 659 * @param b A Bundle to store the display data. 660 * @param dest The file to store the serialized picture data. Will be 661 * overwritten with this WebView's picture data. 662 * @return True if the picture was successfully saved. 663 * @deprecated This method is now obsolete. 664 */ 665 @Deprecated 666 public boolean savePicture(Bundle b, final File dest) { 667 checkThread(); 668 return mProvider.savePicture(b, dest); 669 } 670 671 /** 672 * Restore the display data that was save in {@link #savePicture}. Used in 673 * conjunction with {@link #restoreState}. 674 * 675 * Note that this will not work if the WebView is hardware accelerated. 676 * @param b A Bundle containing the saved display data. 677 * @param src The file where the picture data was stored. 678 * @return True if the picture was successfully restored. 679 * @deprecated This method is now obsolete. 680 */ 681 @Deprecated 682 public boolean restorePicture(Bundle b, File src) { 683 checkThread(); 684 return mProvider.restorePicture(b, src); 685 } 686 687 /** 688 * Restore the state of this WebView from the given map used in 689 * {@link android.app.Activity#onRestoreInstanceState}. This method should 690 * be called to restore the state of the WebView before using the object. If 691 * it is called after the WebView has had a chance to build state (load 692 * pages, create a back/forward list, etc.) there may be undesirable 693 * side-effects. Please note that this method no longer restores the 694 * display data for this WebView. See {@link #savePicture} and {@link 695 * #restorePicture} for saving and restoring the display data. 696 * @param inState The incoming Bundle of state. 697 * @return The restored back/forward list or null if restoreState failed. 698 * @see #savePicture 699 * @see #restorePicture 700 */ 701 public WebBackForwardList restoreState(Bundle inState) { 702 checkThread(); 703 return mProvider.restoreState(inState); 704 } 705 706 /** 707 * Load the given URL with the specified additional HTTP headers. 708 * @param url The URL of the resource to load. 709 * @param additionalHttpHeaders The additional headers to be used in the 710 * HTTP request for this URL, specified as a map from name to 711 * value. Note that if this map contains any of the headers 712 * that are set by default by the WebView, such as those 713 * controlling caching, accept types or the User-Agent, their 714 * values may be overriden by the WebView's defaults. 715 */ 716 public void loadUrl(String url, Map<String, String> additionalHttpHeaders) { 717 checkThread(); 718 mProvider.loadUrl(url, additionalHttpHeaders); 719 } 720 721 /** 722 * Load the given URL. 723 * @param url The URL of the resource to load. 724 */ 725 public void loadUrl(String url) { 726 checkThread(); 727 mProvider.loadUrl(url); 728 } 729 730 /** 731 * Load the url with postData using "POST" method into the WebView. If url 732 * is not a network url, it will be loaded with {link 733 * {@link #loadUrl(String)} instead. 734 * 735 * @param url The url of the resource to load. 736 * @param postData The data will be passed to "POST" request. 737 */ 738 public void postUrl(String url, byte[] postData) { 739 checkThread(); 740 mProvider.postUrl(url, postData); 741 } 742 743 /** 744 * Load the given data into the WebView using a 'data' scheme URL. 745 * <p> 746 * Note that JavaScript's same origin policy means that script running in a 747 * page loaded using this method will be unable to access content loaded 748 * using any scheme other than 'data', including 'http(s)'. To avoid this 749 * restriction, use {@link 750 * #loadDataWithBaseURL(String,String,String,String,String) 751 * loadDataWithBaseURL()} with an appropriate base URL. 752 * <p> 753 * If the value of the encoding parameter is 'base64', then the data must 754 * be encoded as base64. Otherwise, the data must use ASCII encoding for 755 * octets inside the range of safe URL characters and use the standard %xx 756 * hex encoding of URLs for octets outside that range. For example, 757 * '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively. 758 * <p> 759 * The 'data' scheme URL formed by this method uses the default US-ASCII 760 * charset. If you need need to set a different charset, you should form a 761 * 'data' scheme URL which explicitly specifies a charset parameter in the 762 * mediatype portion of the URL and call {@link #loadUrl(String)} instead. 763 * Note that the charset obtained from the mediatype portion of a data URL 764 * always overrides that specified in the HTML or XML document itself. 765 * @param data A String of data in the given encoding. 766 * @param mimeType The MIME type of the data, e.g. 'text/html'. 767 * @param encoding The encoding of the data. 768 */ 769 public void loadData(String data, String mimeType, String encoding) { 770 checkThread(); 771 mProvider.loadData(data, mimeType, encoding); 772 } 773 774 /** 775 * Load the given data into the WebView, using baseUrl as the base URL for 776 * the content. The base URL is used both to resolve relative URLs and when 777 * applying JavaScript's same origin policy. The historyUrl is used for the 778 * history entry. 779 * <p> 780 * Note that content specified in this way can access local device files 781 * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 782 * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'. 783 * <p> 784 * If the base URL uses the data scheme, this method is equivalent to 785 * calling {@link #loadData(String,String,String) loadData()} and the 786 * historyUrl is ignored. 787 * @param baseUrl URL to use as the page's base URL. If null defaults to 788 * 'about:blank' 789 * @param data A String of data in the given encoding. 790 * @param mimeType The MIMEType of the data, e.g. 'text/html'. If null, 791 * defaults to 'text/html'. 792 * @param encoding The encoding of the data. 793 * @param historyUrl URL to use as the history entry, if null defaults to 794 * 'about:blank'. 795 */ 796 public void loadDataWithBaseURL(String baseUrl, String data, 797 String mimeType, String encoding, String historyUrl) { 798 checkThread(); 799 mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); 800 } 801 802 /** 803 * Saves the current view as a web archive. 804 * 805 * @param filename The filename where the archive should be placed. 806 */ 807 public void saveWebArchive(String filename) { 808 checkThread(); 809 mProvider.saveWebArchive(filename); 810 } 811 812 /** 813 * Saves the current view as a web archive. 814 * 815 * @param basename The filename where the archive should be placed. 816 * @param autoname If false, takes basename to be a file. If true, basename 817 * is assumed to be a directory in which a filename will be 818 * chosen according to the url of the current page. 819 * @param callback Called after the web archive has been saved. The 820 * parameter for onReceiveValue will either be the filename 821 * under which the file was saved, or null if saving the 822 * file failed. 823 */ 824 public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) { 825 checkThread(); 826 mProvider.saveWebArchive(basename, autoname, callback); 827 } 828 829 /** 830 * Stop the current load. 831 */ 832 public void stopLoading() { 833 checkThread(); 834 mProvider.stopLoading(); 835 } 836 837 /** 838 * Reload the current url. 839 */ 840 public void reload() { 841 checkThread(); 842 mProvider.reload(); 843 } 844 845 /** 846 * Return true if this WebView has a back history item. 847 * @return True iff this WebView has a back history item. 848 */ 849 public boolean canGoBack() { 850 checkThread(); 851 return mProvider.canGoBack(); 852 } 853 854 /** 855 * Go back in the history of this WebView. 856 */ 857 public void goBack() { 858 checkThread(); 859 mProvider.goBack(); 860 } 861 862 /** 863 * Return true if this WebView has a forward history item. 864 * @return True iff this Webview has a forward history item. 865 */ 866 public boolean canGoForward() { 867 checkThread(); 868 return mProvider.canGoForward(); 869 } 870 871 /** 872 * Go forward in the history of this WebView. 873 */ 874 public void goForward() { 875 checkThread(); 876 mProvider.goForward(); 877 } 878 879 /** 880 * Return true if the page can go back or forward the given 881 * number of steps. 882 * @param steps The negative or positive number of steps to move the 883 * history. 884 */ 885 public boolean canGoBackOrForward(int steps) { 886 checkThread(); 887 return mProvider.canGoBackOrForward(steps); 888 } 889 890 /** 891 * Go to the history item that is the number of steps away from 892 * the current item. Steps is negative if backward and positive 893 * if forward. 894 * @param steps The number of steps to take back or forward in the back 895 * forward list. 896 */ 897 public void goBackOrForward(int steps) { 898 checkThread(); 899 mProvider.goBackOrForward(steps); 900 } 901 902 /** 903 * Returns true if private browsing is enabled in this WebView. 904 */ 905 public boolean isPrivateBrowsingEnabled() { 906 checkThread(); 907 return mProvider.isPrivateBrowsingEnabled(); 908 } 909 910 /** 911 * Scroll the contents of the view up by half the view size 912 * @param top true to jump to the top of the page 913 * @return true if the page was scrolled 914 */ 915 public boolean pageUp(boolean top) { 916 checkThread(); 917 return mProvider.pageUp(top); 918 } 919 920 /** 921 * Scroll the contents of the view down by half the page size 922 * @param bottom true to jump to bottom of page 923 * @return true if the page was scrolled 924 */ 925 public boolean pageDown(boolean bottom) { 926 checkThread(); 927 return mProvider.pageDown(bottom); 928 } 929 930 /** 931 * Clear the view so that onDraw() will draw nothing but white background, 932 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 933 */ 934 public void clearView() { 935 checkThread(); 936 mProvider.clearView(); 937 } 938 939 /** 940 * Return a new picture that captures the current display of the webview. 941 * This is a copy of the display, and will be unaffected if the webview 942 * later loads a different URL. 943 * 944 * @return a picture containing the current contents of the view. Note this 945 * picture is of the entire document, and is not restricted to the 946 * bounds of the view. 947 */ 948 public Picture capturePicture() { 949 checkThread(); 950 return mProvider.capturePicture(); 951 } 952 953 /** 954 * Return the current scale of the WebView 955 * @return The current scale. 956 */ 957 public float getScale() { 958 checkThread(); 959 return mProvider.getScale(); 960 } 961 962 /** 963 * Set the initial scale for the WebView. 0 means default. If 964 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 965 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 966 * WebView starts with this value as initial scale. 967 * Please note that unlike the scale properties in the viewport meta tag, 968 * this method doesn't take the screen density into account. 969 * 970 * @param scaleInPercent The initial scale in percent. 971 */ 972 public void setInitialScale(int scaleInPercent) { 973 checkThread(); 974 mProvider.setInitialScale(scaleInPercent); 975 } 976 977 /** 978 * Invoke the graphical zoom picker widget for this WebView. This will 979 * result in the zoom widget appearing on the screen to control the zoom 980 * level of this WebView. 981 */ 982 public void invokeZoomPicker() { 983 checkThread(); 984 mProvider.invokeZoomPicker(); 985 } 986 987 /** 988 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 989 * is found and the anchor has a non-JavaScript url, the HitTestResult type 990 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 991 * anchor does not have a url or if it is a JavaScript url, the type will 992 * be UNKNOWN_TYPE and the url has to be retrieved through 993 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 994 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 995 * the "extra" field. A type of 996 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 997 * a child node. If a phone number is found, the HitTestResult type is set 998 * to PHONE_TYPE and the phone number is set in the "extra" field of 999 * HitTestResult. If a map address is found, the HitTestResult type is set 1000 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1001 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1002 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1003 * HitTestResult type is set to UNKNOWN_TYPE. 1004 */ 1005 public HitTestResult getHitTestResult() { 1006 checkThread(); 1007 return mProvider.getHitTestResult(); 1008 } 1009 1010 /** 1011 * Request the anchor or image element URL at the last tapped point. 1012 * If hrefMsg is null, this method returns immediately and does not 1013 * dispatch hrefMsg to its target. If the tapped point hits an image, 1014 * an anchor, or an image in an anchor, the message associates 1015 * strings in named keys in its data. The value paired with the key 1016 * may be an empty string. 1017 * 1018 * @param hrefMsg This message will be dispatched with the result of the 1019 * request. The message data contains three keys: 1020 * - "url" returns the anchor's href attribute. 1021 * - "title" returns the anchor's text. 1022 * - "src" returns the image's src attribute. 1023 */ 1024 public void requestFocusNodeHref(Message hrefMsg) { 1025 checkThread(); 1026 mProvider.requestFocusNodeHref(hrefMsg); 1027 } 1028 1029 /** 1030 * Request the url of the image last touched by the user. msg will be sent 1031 * to its target with a String representing the url as its object. 1032 * 1033 * @param msg This message will be dispatched with the result of the request 1034 * as the data member with "url" as key. The result can be null. 1035 */ 1036 public void requestImageRef(Message msg) { 1037 checkThread(); 1038 mProvider.requestImageRef(msg); 1039 } 1040 1041 /** 1042 * Get the url for the current page. This is not always the same as the url 1043 * passed to WebViewClient.onPageStarted because although the load for 1044 * that url has begun, the current page may not have changed. 1045 * @return The url for the current page. 1046 */ 1047 public String getUrl() { 1048 checkThread(); 1049 return mProvider.getUrl(); 1050 } 1051 1052 /** 1053 * Get the original url for the current page. This is not always the same 1054 * as the url passed to WebViewClient.onPageStarted because although the 1055 * load for that url has begun, the current page may not have changed. 1056 * Also, there may have been redirects resulting in a different url to that 1057 * originally requested. 1058 * @return The url that was originally requested for the current page. 1059 */ 1060 public String getOriginalUrl() { 1061 checkThread(); 1062 return mProvider.getOriginalUrl(); 1063 } 1064 1065 /** 1066 * Get the title for the current page. This is the title of the current page 1067 * until WebViewClient.onReceivedTitle is called. 1068 * @return The title for the current page. 1069 */ 1070 public String getTitle() { 1071 checkThread(); 1072 return mProvider.getTitle(); 1073 } 1074 1075 /** 1076 * Get the favicon for the current page. This is the favicon of the current 1077 * page until WebViewClient.onReceivedIcon is called. 1078 * @return The favicon for the current page. 1079 */ 1080 public Bitmap getFavicon() { 1081 checkThread(); 1082 return mProvider.getFavicon(); 1083 } 1084 1085 /** 1086 * Get the touch icon url for the apple-touch-icon <link> element, or 1087 * a URL on this site's server pointing to the standard location of a 1088 * touch icon. 1089 * @hide 1090 */ 1091 public String getTouchIconUrl() { 1092 return mProvider.getTouchIconUrl(); 1093 } 1094 1095 /** 1096 * Get the progress for the current page. 1097 * @return The progress for the current page between 0 and 100. 1098 */ 1099 public int getProgress() { 1100 checkThread(); 1101 return mProvider.getProgress(); 1102 } 1103 1104 /** 1105 * @return the height of the HTML content. 1106 */ 1107 public int getContentHeight() { 1108 checkThread(); 1109 return mProvider.getContentHeight(); 1110 } 1111 1112 /** 1113 * @return the width of the HTML content. 1114 * @hide 1115 */ 1116 public int getContentWidth() { 1117 return mProvider.getContentWidth(); 1118 } 1119 1120 /** 1121 * Pause all layout, parsing, and JavaScript timers for all webviews. This 1122 * is a global requests, not restricted to just this webview. This can be 1123 * useful if the application has been paused. 1124 */ 1125 public void pauseTimers() { 1126 checkThread(); 1127 mProvider.pauseTimers(); 1128 } 1129 1130 /** 1131 * Resume all layout, parsing, and JavaScript timers for all webviews. 1132 * This will resume dispatching all timers. 1133 */ 1134 public void resumeTimers() { 1135 checkThread(); 1136 mProvider.resumeTimers(); 1137 } 1138 1139 /** 1140 * Call this to pause any extra processing associated with this WebView and 1141 * its associated DOM, plugins, JavaScript etc. For example, if the WebView 1142 * is taken offscreen, this could be called to reduce unnecessary CPU or 1143 * network traffic. When the WebView is again "active", call onResume(). 1144 * 1145 * Note that this differs from pauseTimers(), which affects all WebViews. 1146 */ 1147 public void onPause() { 1148 checkThread(); 1149 mProvider.onPause(); 1150 } 1151 1152 /** 1153 * Call this to resume a WebView after a previous call to onPause(). 1154 */ 1155 public void onResume() { 1156 checkThread(); 1157 mProvider.onResume(); 1158 } 1159 1160 /** 1161 * Returns true if the view is paused, meaning onPause() was called. Calling 1162 * onResume() sets the paused state back to false. 1163 * @hide 1164 */ 1165 public boolean isPaused() { 1166 return mProvider.isPaused(); 1167 } 1168 1169 /** 1170 * Call this to inform the view that memory is low so that it can 1171 * free any available memory. 1172 */ 1173 public void freeMemory() { 1174 checkThread(); 1175 mProvider.freeMemory(); 1176 } 1177 1178 /** 1179 * Clear the resource cache. Note that the cache is per-application, so 1180 * this will clear the cache for all WebViews used. 1181 * 1182 * @param includeDiskFiles If false, only the RAM cache is cleared. 1183 */ 1184 public void clearCache(boolean includeDiskFiles) { 1185 checkThread(); 1186 mProvider.clearCache(includeDiskFiles); 1187 } 1188 1189 /** 1190 * Make sure that clearing the form data removes the adapter from the 1191 * currently focused textfield if there is one. 1192 */ 1193 public void clearFormData() { 1194 checkThread(); 1195 mProvider.clearFormData(); 1196 } 1197 1198 /** 1199 * Tell the WebView to clear its internal back/forward list. 1200 */ 1201 public void clearHistory() { 1202 checkThread(); 1203 mProvider.clearHistory(); 1204 } 1205 1206 /** 1207 * Clear the SSL preferences table stored in response to proceeding with SSL 1208 * certificate errors. 1209 */ 1210 public void clearSslPreferences() { 1211 checkThread(); 1212 mProvider.clearSslPreferences(); 1213 } 1214 1215 /** 1216 * Return the WebBackForwardList for this WebView. This contains the 1217 * back/forward list for use in querying each item in the history stack. 1218 * This is a copy of the private WebBackForwardList so it contains only a 1219 * snapshot of the current state. Multiple calls to this method may return 1220 * different objects. The object returned from this method will not be 1221 * updated to reflect any new state. 1222 */ 1223 public WebBackForwardList copyBackForwardList() { 1224 checkThread(); 1225 return mProvider.copyBackForwardList(); 1226 1227 } 1228 1229 /** 1230 * Register the interface to be used when a find-on-page result has become 1231 * available. This will replace the current handler. 1232 * 1233 * @param listener An implementation of FindListener 1234 * @hide 1235 */ 1236 public void setFindListener(FindListener listener) { 1237 checkThread(); 1238 mProvider.setFindListener(listener); 1239 } 1240 1241 /** 1242 * Highlight and scroll to the next occurance of String in findAll. 1243 * Wraps the page infinitely, and scrolls. Must be called after 1244 * calling findAll. 1245 * 1246 * @param forward Direction to search. 1247 */ 1248 public void findNext(boolean forward) { 1249 checkThread(); 1250 mProvider.findNext(forward); 1251 } 1252 1253 /** 1254 * Find all instances of find on the page and highlight them. 1255 * 1256 * @param find String to find. 1257 * @return int The number of occurances of the String "find" 1258 * that were found. 1259 */ 1260 public int findAll(String find) { 1261 checkThread(); 1262 return mProvider.findAll(find); 1263 } 1264 1265 /** 1266 * Find all instances of find on the page and highlight them, 1267 * asynchronously. 1268 * 1269 * @param find String to find. 1270 * @hide 1271 */ 1272 public void findAllAsync(String find) { 1273 checkThread(); 1274 mProvider.findAllAsync(find); 1275 } 1276 1277 /** 1278 * Start an ActionMode for finding text in this WebView. Only works if this 1279 * WebView is attached to the view system. 1280 * @param text If non-null, will be the initial text to search for. 1281 * Otherwise, the last String searched for in this WebView will 1282 * be used to start. 1283 * @param showIme If true, show the IME, assuming the user will begin typing. 1284 * If false and text is non-null, perform a find all. 1285 * @return boolean True if the find dialog is shown, false otherwise. 1286 */ 1287 public boolean showFindDialog(String text, boolean showIme) { 1288 checkThread(); 1289 return mProvider.showFindDialog(text, showIme); 1290 } 1291 1292 /** 1293 * Return the first substring consisting of the address of a physical 1294 * location. Currently, only addresses in the United States are detected, 1295 * and consist of: 1296 * - a house number 1297 * - a street name 1298 * - a street type (Road, Circle, etc), either spelled out or abbreviated 1299 * - a city name 1300 * - a state or territory, either spelled out or two-letter abbr. 1301 * - an optional 5 digit or 9 digit zip code. 1302 * 1303 * All names must be correctly capitalized, and the zip code, if present, 1304 * must be valid for the state. The street type must be a standard USPS 1305 * spelling or abbreviation. The state or territory must also be spelled 1306 * or abbreviated using USPS standards. The house number may not exceed 1307 * five digits. 1308 * @param addr The string to search for addresses. 1309 * 1310 * @return the address, or if no address is found, return null. 1311 */ 1312 public static String findAddress(String addr) { 1313 checkThread(); 1314 return getFactory().getStatics().findAddress(addr); 1315 } 1316 1317 /* 1318 * Clear the highlighting surrounding text matches created by findAll. 1319 */ 1320 public void clearMatches() { 1321 checkThread(); 1322 mProvider.clearMatches(); 1323 } 1324 1325 /** 1326 * Query the document to see if it contains any image references. The 1327 * message object will be dispatched with arg1 being set to 1 if images 1328 * were found and 0 if the document does not reference any images. 1329 * @param response The message that will be dispatched with the result. 1330 */ 1331 public void documentHasImages(Message response) { 1332 checkThread(); 1333 mProvider.documentHasImages(response); 1334 } 1335 1336 /** 1337 * Set the WebViewClient that will receive various notifications and 1338 * requests. This will replace the current handler. 1339 * @param client An implementation of WebViewClient. 1340 */ 1341 public void setWebViewClient(WebViewClient client) { 1342 checkThread(); 1343 mProvider.setWebViewClient(client); 1344 } 1345 1346 /** 1347 * Register the interface to be used when content can not be handled by 1348 * the rendering engine, and should be downloaded instead. This will replace 1349 * the current handler. 1350 * @param listener An implementation of DownloadListener. 1351 */ 1352 public void setDownloadListener(DownloadListener listener) { 1353 checkThread(); 1354 mProvider.setDownloadListener(listener); 1355 } 1356 1357 /** 1358 * Set the chrome handler. This is an implementation of WebChromeClient for 1359 * use in handling JavaScript dialogs, favicons, titles, and the progress. 1360 * This will replace the current handler. 1361 * @param client An implementation of WebChromeClient. 1362 */ 1363 public void setWebChromeClient(WebChromeClient client) { 1364 checkThread(); 1365 mProvider.setWebChromeClient(client); 1366 } 1367 1368 /** 1369 * Set the Picture listener. This is an interface used to receive 1370 * notifications of a new Picture. 1371 * @param listener An implementation of WebView.PictureListener. 1372 * @deprecated This method is now obsolete. 1373 */ 1374 @Deprecated 1375 public void setPictureListener(PictureListener listener) { 1376 checkThread(); 1377 mProvider.setPictureListener(listener); 1378 } 1379 1380 /** 1381 * This method injects the supplied Java object into the WebView. The 1382 * object is injected into the JavaScript context of the main frame, using 1383 * the supplied name. This allows the Java object to be accessed from 1384 * JavaScript. Note that that injected objects will not appear in 1385 * JavaScript until the page is next (re)loaded. For example: 1386 * <pre> webView.addJavascriptInterface(new Object(), "injectedObject"); 1387 * webView.loadData("<!DOCTYPE html><title></title>", "text/html", null); 1388 * webView.loadUrl("javascript:alert(injectedObject.toString())");</pre> 1389 * <p><strong>IMPORTANT:</strong> 1390 * <ul> 1391 * <li> addJavascriptInterface() can be used to allow JavaScript to control 1392 * the host application. This is a powerful feature, but also presents a 1393 * security risk. Use of this method in a WebView containing untrusted 1394 * content could allow an attacker to manipulate the host application in 1395 * unintended ways, executing Java code with the permissions of the host 1396 * application. Use extreme care when using this method in a WebView which 1397 * could contain untrusted content. 1398 * <li> JavaScript interacts with Java object on a private, background 1399 * thread of the WebView. Care is therefore required to maintain thread 1400 * safety.</li> 1401 * </ul></p> 1402 * @param object The Java object to inject into the WebView's JavaScript 1403 * context. Null values are ignored. 1404 * @param name The name used to expose the instance in JavaScript. 1405 */ 1406 public void addJavascriptInterface(Object object, String name) { 1407 checkThread(); 1408 mProvider.addJavascriptInterface(object, name); 1409 } 1410 1411 /** 1412 * Removes a previously added JavaScript interface with the given name. 1413 * @param interfaceName The name of the interface to remove. 1414 */ 1415 public void removeJavascriptInterface(String interfaceName) { 1416 checkThread(); 1417 mProvider.removeJavascriptInterface(interfaceName); 1418 } 1419 1420 /** 1421 * Return the WebSettings object used to control the settings for this 1422 * WebView. 1423 * @return A WebSettings object that can be used to control this WebView's 1424 * settings. 1425 */ 1426 public WebSettings getSettings() { 1427 checkThread(); 1428 return mProvider.getSettings(); 1429 } 1430 1431 /** 1432 * Return the list of currently loaded plugins. 1433 * @return The list of currently loaded plugins. 1434 * 1435 * @hide 1436 * @deprecated This was used for Gears, which has been deprecated. 1437 */ 1438 @Deprecated 1439 public static synchronized PluginList getPluginList() { 1440 checkThread(); 1441 return new PluginList(); 1442 } 1443 1444 /** 1445 * @hide 1446 * @deprecated This was used for Gears, which has been deprecated. 1447 */ 1448 @Deprecated 1449 public void refreshPlugins(boolean reloadOpenPages) { 1450 checkThread(); 1451 } 1452 1453 /** 1454 * Use this method to put the WebView into text selection mode. 1455 * Do not rely on this functionality; it will be deprecated in the future. 1456 * @deprecated This method is now obsolete. 1457 */ 1458 @Deprecated 1459 public void emulateShiftHeld() { 1460 checkThread(); 1461 mProvider.emulateShiftHeld(); 1462 } 1463 1464 /** 1465 * @deprecated WebView no longer needs to implement 1466 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1467 */ 1468 @Override 1469 // Cannot add @hide as this can always be accessed via the interface. 1470 @Deprecated 1471 public void onChildViewAdded(View parent, View child) {} 1472 1473 /** 1474 * @deprecated WebView no longer needs to implement 1475 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 1476 */ 1477 @Override 1478 // Cannot add @hide as this can always be accessed via the interface. 1479 @Deprecated 1480 public void onChildViewRemoved(View p, View child) {} 1481 1482 /** 1483 * @deprecated WebView should not have implemented 1484 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 1485 */ 1486 @Override 1487 // Cannot add @hide as this can always be accessed via the interface. 1488 @Deprecated 1489 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 1490 } 1491 1492 public void setMapTrackballToArrowKeys(boolean setMap) { 1493 checkThread(); 1494 mProvider.setMapTrackballToArrowKeys(setMap); 1495 } 1496 1497 1498 public void flingScroll(int vx, int vy) { 1499 checkThread(); 1500 mProvider.flingScroll(vx, vy); 1501 } 1502 1503 /** 1504 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 1505 * in charge of installing this view to the view hierarchy. This view will 1506 * become visible when the user starts scrolling via touch and fade away if 1507 * the user does not interact with it. 1508 * <p/> 1509 * API version 3 introduces a built-in zoom mechanism that is shown 1510 * automatically by the MapView. This is the preferred approach for 1511 * showing the zoom UI. 1512 * 1513 * @deprecated The built-in zoom mechanism is preferred, see 1514 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 1515 */ 1516 @Deprecated 1517 public View getZoomControls() { 1518 checkThread(); 1519 return mProvider.getZoomControls(); 1520 } 1521 1522 /** 1523 * @return TRUE if the WebView can be zoomed in. 1524 */ 1525 public boolean canZoomIn() { 1526 checkThread(); 1527 return mProvider.canZoomIn(); 1528 } 1529 1530 /** 1531 * @return TRUE if the WebView can be zoomed out. 1532 */ 1533 public boolean canZoomOut() { 1534 checkThread(); 1535 return mProvider.canZoomOut(); 1536 } 1537 1538 /** 1539 * Perform zoom in in the webview 1540 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 1541 */ 1542 public boolean zoomIn() { 1543 checkThread(); 1544 return mProvider.zoomIn(); 1545 } 1546 1547 /** 1548 * Perform zoom out in the webview 1549 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 1550 */ 1551 public boolean zoomOut() { 1552 checkThread(); 1553 return mProvider.zoomOut(); 1554 } 1555 1556 /** 1557 * @deprecated This method is now obsolete. 1558 */ 1559 @Deprecated 1560 public void debugDump() { 1561 checkThread(); 1562 mProvider.debugDump(); 1563 } 1564 1565 //------------------------------------------------------------------------- 1566 // Interface for WebView providers 1567 //------------------------------------------------------------------------- 1568 1569 /** 1570 * Used by providers to obtain the underlying implementation, e.g. when the appliction 1571 * responds to WebViewClient.onCreateWindow() request. 1572 * 1573 * @hide WebViewProvider is not public API. 1574 */ 1575 public WebViewProvider getWebViewProvider() { 1576 return mProvider; 1577 } 1578 1579 /** 1580 * Callback interface, allows the provider implementation to access non-public methods 1581 * and fields, and make super-class calls in this WebView instance. 1582 * @hide Only for use by WebViewProvider implementations 1583 */ 1584 public class PrivateAccess { 1585 // ---- Access to super-class methods ---- 1586 public int super_getScrollBarStyle() { 1587 return WebView.super.getScrollBarStyle(); 1588 } 1589 1590 public void super_scrollTo(int scrollX, int scrollY) { 1591 WebView.super.scrollTo(scrollX, scrollY); 1592 } 1593 1594 public void super_computeScroll() { 1595 WebView.super.computeScroll(); 1596 } 1597 1598 public boolean super_performLongClick() { 1599 return WebView.super.performLongClick(); 1600 } 1601 1602 public boolean super_setFrame(int left, int top, int right, int bottom) { 1603 return WebView.super.setFrame(left, top, right, bottom); 1604 } 1605 1606 public boolean super_dispatchKeyEvent(KeyEvent event) { 1607 return WebView.super.dispatchKeyEvent(event); 1608 } 1609 1610 public boolean super_onGenericMotionEvent(MotionEvent event) { 1611 return WebView.super.onGenericMotionEvent(event); 1612 } 1613 1614 public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) { 1615 return WebView.super.requestFocus(direction, previouslyFocusedRect); 1616 } 1617 1618 public void super_setLayoutParams(ViewGroup.LayoutParams params) { 1619 WebView.super.setLayoutParams(params); 1620 } 1621 1622 // ---- Access to non-public methods ---- 1623 public void overScrollBy(int deltaX, int deltaY, 1624 int scrollX, int scrollY, 1625 int scrollRangeX, int scrollRangeY, 1626 int maxOverScrollX, int maxOverScrollY, 1627 boolean isTouchEvent) { 1628 WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, 1629 maxOverScrollX, maxOverScrollY, isTouchEvent); 1630 } 1631 1632 public void awakenScrollBars(int duration) { 1633 WebView.this.awakenScrollBars(duration); 1634 } 1635 1636 public void awakenScrollBars(int duration, boolean invalidate) { 1637 WebView.this.awakenScrollBars(duration, invalidate); 1638 } 1639 1640 public float getVerticalScrollFactor() { 1641 return WebView.this.getVerticalScrollFactor(); 1642 } 1643 1644 public float getHorizontalScrollFactor() { 1645 return WebView.this.getHorizontalScrollFactor(); 1646 } 1647 1648 public void setMeasuredDimension(int measuredWidth, int measuredHeight) { 1649 WebView.this.setMeasuredDimension(measuredWidth, measuredHeight); 1650 } 1651 1652 public void onScrollChanged(int l, int t, int oldl, int oldt) { 1653 WebView.this.onScrollChanged(l, t, oldl, oldt); 1654 } 1655 1656 public int getHorizontalScrollbarHeight() { 1657 return WebView.this.getHorizontalScrollbarHeight(); 1658 } 1659 1660 // ---- Access to (non-public) fields ---- 1661 /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */ 1662 public void setScrollXRaw(int scrollX) { 1663 WebView.this.mScrollX = scrollX; 1664 } 1665 1666 /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */ 1667 public void setScrollYRaw(int scrollY) { 1668 WebView.this.mScrollY = scrollY; 1669 } 1670 1671 } 1672 1673 //------------------------------------------------------------------------- 1674 // Private internal stuff 1675 //------------------------------------------------------------------------- 1676 1677 // Cache the factory both for efficiency, and ensure any one process gets all webviews from the 1678 // same provider. 1679 private static WebViewFactoryProvider sProviderFactory; 1680 1681 private WebViewProvider mProvider; 1682 1683 private void ensureProviderCreated() { 1684 checkThread(); 1685 if (mProvider == null) { 1686 if (DEBUG) Log.v(LOGTAG, "instantiating webview provider instance"); 1687 // As this can get called during the base class constructor chain, pass the minimum 1688 // number of dependencies here; the rest are deferred to init(). 1689 mProvider = getFactory().createWebView(this, new PrivateAccess()); 1690 } 1691 } 1692 1693 private static synchronized WebViewFactoryProvider getFactory() { 1694 // For now the main purpose of this function (and the factory abstration) is to keep 1695 // us honest and minimize usage of WebViewClassic internals when binding the proxy. 1696 checkThread(); 1697 if (sProviderFactory != null) return sProviderFactory; 1698 1699 sProviderFactory = getFactoryByName(DEFAULT_WEB_VIEW_FACTORY); 1700 if (sProviderFactory == null) { 1701 if (DEBUG) Log.v (LOGTAG, "Falling back to explicit linkage"); 1702 sProviderFactory = new WebViewClassic.Factory(); 1703 } 1704 return sProviderFactory; 1705 } 1706 1707 private static WebViewFactoryProvider getFactoryByName(String providerName) { 1708 try { 1709 if (DEBUG) Log.v(LOGTAG, "attempt to load class " + providerName); 1710 Class<?> c = Class.forName(providerName); 1711 if (DEBUG) Log.v(LOGTAG, "instantiating factory"); 1712 return (WebViewFactoryProvider) c.newInstance(); 1713 } catch (ClassNotFoundException e) { 1714 Log.e(LOGTAG, "error loading " + providerName, e); 1715 } catch (IllegalAccessException e) { 1716 Log.e(LOGTAG, "error loading " + providerName, e); 1717 } catch (InstantiationException e) { 1718 Log.e(LOGTAG, "error loading " + providerName, e); 1719 } 1720 return null; 1721 } 1722 1723 private static void checkThread() { 1724 if (Looper.myLooper() != Looper.getMainLooper()) { 1725 Throwable throwable = new Throwable( 1726 "Warning: A WebView method was called on thread '" + 1727 Thread.currentThread().getName() + "'. " + 1728 "All WebView methods must be called on the UI thread. " + 1729 "Future versions of WebView may not support use on other threads."); 1730 Log.w(LOGTAG, Log.getStackTraceString(throwable)); 1731 StrictMode.onWebViewMethodCalledOnWrongThread(throwable); 1732 } 1733 } 1734 1735 //------------------------------------------------------------------------- 1736 // Override View methods 1737 //------------------------------------------------------------------------- 1738 1739 // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures 1740 // there's a corresponding override (or better, caller) for each of them in here. 1741 1742 @Override 1743 protected void onAttachedToWindow() { 1744 super.onAttachedToWindow(); 1745 mProvider.getViewDelegate().onAttachedToWindow(); 1746 } 1747 1748 @Override 1749 protected void onDetachedFromWindow() { 1750 mProvider.getViewDelegate().onDetachedFromWindow(); 1751 super.onDetachedFromWindow(); 1752 } 1753 1754 @Override 1755 public void setLayoutParams(ViewGroup.LayoutParams params) { 1756 mProvider.getViewDelegate().setLayoutParams(params); 1757 } 1758 1759 @Override 1760 public void setOverScrollMode(int mode) { 1761 super.setOverScrollMode(mode); 1762 // This method may called in the constructor chain, before the WebView provider is 1763 // created. (Fortunately, this is the only method we override that can get called by 1764 // any of the base class constructors). 1765 ensureProviderCreated(); 1766 mProvider.getViewDelegate().setOverScrollMode(mode); 1767 } 1768 1769 @Override 1770 public void setScrollBarStyle(int style) { 1771 mProvider.getViewDelegate().setScrollBarStyle(style); 1772 super.setScrollBarStyle(style); 1773 } 1774 1775 @Override 1776 protected int computeHorizontalScrollRange() { 1777 return mProvider.getScrollDelegate().computeHorizontalScrollRange(); 1778 } 1779 1780 @Override 1781 protected int computeHorizontalScrollOffset() { 1782 return mProvider.getScrollDelegate().computeHorizontalScrollOffset(); 1783 } 1784 1785 @Override 1786 protected int computeVerticalScrollRange() { 1787 return mProvider.getScrollDelegate().computeVerticalScrollRange(); 1788 } 1789 1790 @Override 1791 protected int computeVerticalScrollOffset() { 1792 return mProvider.getScrollDelegate().computeVerticalScrollOffset(); 1793 } 1794 1795 @Override 1796 protected int computeVerticalScrollExtent() { 1797 return mProvider.getScrollDelegate().computeVerticalScrollExtent(); 1798 } 1799 1800 @Override 1801 public void computeScroll() { 1802 mProvider.getScrollDelegate().computeScroll(); 1803 } 1804 1805 @Override 1806 public boolean onHoverEvent(MotionEvent event) { 1807 return mProvider.getViewDelegate().onHoverEvent(event); 1808 } 1809 1810 @Override 1811 public boolean onTouchEvent(MotionEvent event) { 1812 return mProvider.getViewDelegate().onTouchEvent(event); 1813 } 1814 1815 @Override 1816 public boolean onGenericMotionEvent(MotionEvent event) { 1817 return mProvider.getViewDelegate().onGenericMotionEvent(event); 1818 } 1819 1820 @Override 1821 public boolean onTrackballEvent(MotionEvent event) { 1822 return mProvider.getViewDelegate().onTrackballEvent(event); 1823 } 1824 1825 @Override 1826 public boolean onKeyDown(int keyCode, KeyEvent event) { 1827 return mProvider.getViewDelegate().onKeyDown(keyCode, event); 1828 } 1829 1830 @Override 1831 public boolean onKeyUp(int keyCode, KeyEvent event) { 1832 return mProvider.getViewDelegate().onKeyUp(keyCode, event); 1833 } 1834 1835 @Override 1836 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 1837 return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event); 1838 } 1839 1840 /* 1841 TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not 1842 to be delegating them too. 1843 1844 @Override 1845 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 1846 return mProvider.getViewDelegate().onKeyPreIme(keyCode, event); 1847 } 1848 @Override 1849 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 1850 return mProvider.getViewDelegate().onKeyLongPress(keyCode, event); 1851 } 1852 @Override 1853 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 1854 return mProvider.getViewDelegate().onKeyShortcut(keyCode, event); 1855 } 1856 */ 1857 1858 @Deprecated 1859 @Override 1860 public boolean shouldDelayChildPressedState() { 1861 return mProvider.getViewDelegate().shouldDelayChildPressedState(); 1862 } 1863 1864 @Override 1865 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 1866 super.onInitializeAccessibilityNodeInfo(info); 1867 mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info); 1868 } 1869 1870 @Override 1871 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1872 super.onInitializeAccessibilityEvent(event); 1873 mProvider.getViewDelegate().onInitializeAccessibilityEvent(event); 1874 } 1875 1876 /** @hide */ 1877 @Override 1878 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 1879 int l, int t, int r, int b) { 1880 mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); 1881 } 1882 1883 @Override 1884 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { 1885 mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY); 1886 } 1887 1888 @Override 1889 protected void onWindowVisibilityChanged(int visibility) { 1890 super.onWindowVisibilityChanged(visibility); 1891 mProvider.getViewDelegate().onWindowVisibilityChanged(visibility); 1892 } 1893 1894 @Override 1895 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 1896 // Not using short-circuit OR: provider does suppress base-class call. 1897 return mProvider.getViewDelegate().drawChild(canvas, child, drawingTime) | 1898 super.drawChild(canvas, child, drawingTime); 1899 } 1900 1901 @Override 1902 protected void onDraw(Canvas canvas) { 1903 mProvider.getViewDelegate().onDraw(canvas); 1904 } 1905 1906 @Override 1907 public boolean performLongClick() { 1908 return mProvider.getViewDelegate().performLongClick(); 1909 } 1910 1911 @Override 1912 protected void onConfigurationChanged(Configuration newConfig) { 1913 mProvider.getViewDelegate().onConfigurationChanged(newConfig); 1914 } 1915 1916 @Override 1917 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 1918 return mProvider.getViewDelegate().onCreateInputConnection(outAttrs); 1919 } 1920 1921 @Override 1922 protected void onVisibilityChanged(View changedView, int visibility) { 1923 super.onVisibilityChanged(changedView, visibility); 1924 mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility); 1925 } 1926 1927 @Override 1928 public void onWindowFocusChanged(boolean hasWindowFocus) { 1929 mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus); 1930 super.onWindowFocusChanged(hasWindowFocus); 1931 } 1932 1933 @Override 1934 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 1935 mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect); 1936 super.onFocusChanged(focused, direction, previouslyFocusedRect); 1937 } 1938 1939 /** @hide */ 1940 @Override 1941 protected boolean setFrame(int left, int top, int right, int bottom) { 1942 return mProvider.getViewDelegate().setFrame(left, top, right, bottom); 1943 } 1944 1945 @Override 1946 protected void onSizeChanged(int w, int h, int ow, int oh) { 1947 super.onSizeChanged(w, h, ow, oh); 1948 mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh); 1949 } 1950 1951 @Override 1952 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 1953 super.onScrollChanged(l, t, oldl, oldt); 1954 mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt); 1955 } 1956 1957 @Override 1958 public boolean dispatchKeyEvent(KeyEvent event) { 1959 return mProvider.getViewDelegate().dispatchKeyEvent(event); 1960 } 1961 1962 @Override 1963 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 1964 return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect); 1965 } 1966 1967 @Deprecated 1968 @Override 1969 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1970 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1971 mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec); 1972 } 1973 1974 @Override 1975 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 1976 return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate); 1977 } 1978 1979 @Override 1980 public void setBackgroundColor(int color) { 1981 mProvider.getViewDelegate().setBackgroundColor(color); 1982 } 1983} 1984