• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 
17 package android.webkit;
18 
19 import android.graphics.Bitmap;
20 import android.net.http.SslError;
21 import android.os.Message;
22 import android.view.InputEvent;
23 import android.view.KeyEvent;
24 import android.view.ViewRootImpl;
25 
26 public class WebViewClient {
27 
28     /**
29      * Give the host application a chance to take over the control when a new
30      * url is about to be loaded in the current WebView. If WebViewClient is not
31      * provided, by default WebView will ask Activity Manager to choose the
32      * proper handler for the url. If WebViewClient is provided, return true
33      * means the host application handles the url, while return false means the
34      * current WebView handles the url.
35      * This method is not called for requests using the POST "method".
36      *
37      * @param view The WebView that is initiating the callback.
38      * @param url The url to be loaded.
39      * @return True if the host application wants to leave the current WebView
40      *         and handle the url itself, otherwise return false.
41      */
shouldOverrideUrlLoading(WebView view, String url)42     public boolean shouldOverrideUrlLoading(WebView view, String url) {
43         return false;
44     }
45 
46     /**
47      * Notify the host application that a page has started loading. This method
48      * is called once for each main frame load so a page with iframes or
49      * framesets will call onPageStarted one time for the main frame. This also
50      * means that onPageStarted will not be called when the contents of an
51      * embedded frame changes, i.e. clicking a link whose target is an iframe,
52      * it will also not be called for fragment navigations (navigations to
53      * #fragment_id).
54      *
55      * @param view The WebView that is initiating the callback.
56      * @param url The url to be loaded.
57      * @param favicon The favicon for this page if it already exists in the
58      *            database.
59      */
onPageStarted(WebView view, String url, Bitmap favicon)60     public void onPageStarted(WebView view, String url, Bitmap favicon) {
61     }
62 
63     /**
64      * Notify the host application that a page has finished loading. This method
65      * is called only for main frame. When onPageFinished() is called, the
66      * rendering picture may not be updated yet. To get the notification for the
67      * new Picture, use {@link WebView.PictureListener#onNewPicture}.
68      *
69      * @param view The WebView that is initiating the callback.
70      * @param url The url of the page.
71      */
onPageFinished(WebView view, String url)72     public void onPageFinished(WebView view, String url) {
73     }
74 
75     /**
76      * Notify the host application that the WebView will load the resource
77      * specified by the given url.
78      *
79      * @param view The WebView that is initiating the callback.
80      * @param url The url of the resource the WebView will load.
81      */
onLoadResource(WebView view, String url)82     public void onLoadResource(WebView view, String url) {
83     }
84 
85     /**
86      * Notify the host application that {@link android.webkit.WebView} content left over from
87      * previous page navigations will no longer be drawn.
88      *
89      * <p>This callback can be used to determine the point at which it is safe to make a recycled
90      * {@link android.webkit.WebView} visible, ensuring that no stale content is shown. It is called
91      * at the earliest point at which it can be guaranteed that {@link WebView#onDraw} will no
92      * longer draw any content from previous navigations. The next draw will display either the
93      * {@link WebView#setBackgroundColor background color} of the {@link WebView}, or some of the
94      * contents of the newly loaded page.
95      *
96      * <p>This method is called when the body of the HTTP response has started loading, is reflected
97      * in the DOM, and will be visible in subsequent draws. This callback occurs early in the
98      * document loading process, and as such you should expect that linked resources (for example,
99      * css and images) may not be available.</p>
100      *
101      * <p>For more fine-grained notification of visual state updates, see {@link
102      * WebView#postVisualStateCallback}.</p>
103      *
104      * <p>Please note that all the conditions and recommendations applicable to
105      * {@link WebView#postVisualStateCallback} also apply to this API.<p>
106      *
107      * <p>This callback is only called for main frame navigations.</p>
108      *
109      * @param view The {@link android.webkit.WebView} for which the navigation occurred.
110      * @param url  The URL corresponding to the page navigation that triggered this callback.
111      */
onPageCommitVisible(WebView view, String url)112     public void onPageCommitVisible(WebView view, String url) {
113     }
114 
115     /**
116      * Notify the host application of a resource request and allow the
117      * application to return the data.  If the return value is null, the WebView
118      * will continue to load the resource as usual.  Otherwise, the return
119      * response and data will be used.  NOTE: This method is called on a thread
120      * other than the UI thread so clients should exercise caution
121      * when accessing private data or the view system.
122      *
123      * @param view The {@link android.webkit.WebView} that is requesting the
124      *             resource.
125      * @param url The raw url of the resource.
126      * @return A {@link android.webkit.WebResourceResponse} containing the
127      *         response information or null if the WebView should load the
128      *         resource itself.
129      * @deprecated Use {@link #shouldInterceptRequest(WebView, WebResourceRequest)
130      *             shouldInterceptRequest(WebView, WebResourceRequest)} instead.
131      */
132     @Deprecated
shouldInterceptRequest(WebView view, String url)133     public WebResourceResponse shouldInterceptRequest(WebView view,
134             String url) {
135         return null;
136     }
137 
138     /**
139      * Notify the host application of a resource request and allow the
140      * application to return the data.  If the return value is null, the WebView
141      * will continue to load the resource as usual.  Otherwise, the return
142      * response and data will be used.  NOTE: This method is called on a thread
143      * other than the UI thread so clients should exercise caution
144      * when accessing private data or the view system.
145      *
146      * @param view The {@link android.webkit.WebView} that is requesting the
147      *             resource.
148      * @param request Object containing the details of the request.
149      * @return A {@link android.webkit.WebResourceResponse} containing the
150      *         response information or null if the WebView should load the
151      *         resource itself.
152      */
shouldInterceptRequest(WebView view, WebResourceRequest request)153     public WebResourceResponse shouldInterceptRequest(WebView view,
154             WebResourceRequest request) {
155         return shouldInterceptRequest(view, request.getUrl().toString());
156     }
157 
158     /**
159      * Notify the host application that there have been an excessive number of
160      * HTTP redirects. As the host application if it would like to continue
161      * trying to load the resource. The default behavior is to send the cancel
162      * message.
163      *
164      * @param view The WebView that is initiating the callback.
165      * @param cancelMsg The message to send if the host wants to cancel
166      * @param continueMsg The message to send if the host wants to continue
167      * @deprecated This method is no longer called. When the WebView encounters
168      *             a redirect loop, it will cancel the load.
169      */
170     @Deprecated
onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg)171     public void onTooManyRedirects(WebView view, Message cancelMsg,
172             Message continueMsg) {
173         cancelMsg.sendToTarget();
174     }
175 
176     // These ints must match up to the hidden values in EventHandler.
177     /** Generic error */
178     public static final int ERROR_UNKNOWN = -1;
179     /** Server or proxy hostname lookup failed */
180     public static final int ERROR_HOST_LOOKUP = -2;
181     /** Unsupported authentication scheme (not basic or digest) */
182     public static final int ERROR_UNSUPPORTED_AUTH_SCHEME = -3;
183     /** User authentication failed on server */
184     public static final int ERROR_AUTHENTICATION = -4;
185     /** User authentication failed on proxy */
186     public static final int ERROR_PROXY_AUTHENTICATION = -5;
187     /** Failed to connect to the server */
188     public static final int ERROR_CONNECT = -6;
189     /** Failed to read or write to the server */
190     public static final int ERROR_IO = -7;
191     /** Connection timed out */
192     public static final int ERROR_TIMEOUT = -8;
193     /** Too many redirects */
194     public static final int ERROR_REDIRECT_LOOP = -9;
195     /** Unsupported URI scheme */
196     public static final int ERROR_UNSUPPORTED_SCHEME = -10;
197     /** Failed to perform SSL handshake */
198     public static final int ERROR_FAILED_SSL_HANDSHAKE = -11;
199     /** Malformed URL */
200     public static final int ERROR_BAD_URL = -12;
201     /** Generic file error */
202     public static final int ERROR_FILE = -13;
203     /** File not found */
204     public static final int ERROR_FILE_NOT_FOUND = -14;
205     /** Too many requests during this load */
206     public static final int ERROR_TOO_MANY_REQUESTS = -15;
207 
208     /**
209      * Report an error to the host application. These errors are unrecoverable
210      * (i.e. the main resource is unavailable). The errorCode parameter
211      * corresponds to one of the ERROR_* constants.
212      * @param view The WebView that is initiating the callback.
213      * @param errorCode The error code corresponding to an ERROR_* value.
214      * @param description A String describing the error.
215      * @param failingUrl The url that failed to load.
216      * @deprecated Use {@link #onReceivedError(WebView, WebResourceRequest, WebResourceError)
217      *             onReceivedError(WebView, WebResourceRequest, WebResourceError)} instead.
218      */
219     @Deprecated
onReceivedError(WebView view, int errorCode, String description, String failingUrl)220     public void onReceivedError(WebView view, int errorCode,
221             String description, String failingUrl) {
222     }
223 
224     /**
225      * Report web resource loading error to the host application. These errors usually indicate
226      * inability to connect to the server. Note that unlike the deprecated version of the callback,
227      * the new version will be called for any resource (iframe, image, etc), not just for the main
228      * page. Thus, it is recommended to perform minimum required work in this callback.
229      * @param view The WebView that is initiating the callback.
230      * @param request The originating request.
231      * @param error Information about the error occured.
232      */
onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)233     public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
234         if (request.isForMainFrame()) {
235             onReceivedError(view,
236                     error.getErrorCode(), error.getDescription().toString(),
237                     request.getUrl().toString());
238         }
239     }
240 
241     /**
242      * Notify the host application that an HTTP error has been received from the server while
243      * loading a resource.  HTTP errors have status codes &gt;= 400.  This callback will be called
244      * for any resource (iframe, image, etc), not just for the main page. Thus, it is recommended to
245      * perform minimum required work in this callback. Note that the content of the server
246      * response may not be provided within the <b>errorResponse</b> parameter.
247      * @param view The WebView that is initiating the callback.
248      * @param request The originating request.
249      * @param errorResponse Information about the error occured.
250      */
onReceivedHttpError( WebView view, WebResourceRequest request, WebResourceResponse errorResponse)251     public void onReceivedHttpError(
252             WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
253     }
254 
255     /**
256      * As the host application if the browser should resend data as the
257      * requested page was a result of a POST. The default is to not resend the
258      * data.
259      *
260      * @param view The WebView that is initiating the callback.
261      * @param dontResend The message to send if the browser should not resend
262      * @param resend The message to send if the browser should resend data
263      */
onFormResubmission(WebView view, Message dontResend, Message resend)264     public void onFormResubmission(WebView view, Message dontResend,
265             Message resend) {
266         dontResend.sendToTarget();
267     }
268 
269     /**
270      * Notify the host application to update its visited links database.
271      *
272      * @param view The WebView that is initiating the callback.
273      * @param url The url being visited.
274      * @param isReload True if this url is being reloaded.
275      */
doUpdateVisitedHistory(WebView view, String url, boolean isReload)276     public void doUpdateVisitedHistory(WebView view, String url,
277             boolean isReload) {
278     }
279 
280     /**
281      * Notify the host application that an SSL error occurred while loading a
282      * resource. The host application must call either handler.cancel() or
283      * handler.proceed(). Note that the decision may be retained for use in
284      * response to future SSL errors. The default behavior is to cancel the
285      * load.
286      *
287      * @param view The WebView that is initiating the callback.
288      * @param handler An SslErrorHandler object that will handle the user's
289      *            response.
290      * @param error The SSL error object.
291      */
onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)292     public void onReceivedSslError(WebView view, SslErrorHandler handler,
293             SslError error) {
294         handler.cancel();
295     }
296 
297     /**
298      * Notify the host application to handle a SSL client certificate
299      * request. The host application is responsible for showing the UI
300      * if desired and providing the keys. There are three ways to
301      * respond: proceed(), cancel() or ignore(). Webview stores the response
302      * in memory (for the life of the application) if proceed() or cancel() is
303      * called and does not call onReceivedClientCertRequest() again for the
304      * same host and port pair. Webview does not store the response if ignore()
305      * is called.
306      *
307      * This method is called on the UI thread. During the callback, the
308      * connection is suspended.
309      *
310      * For most use cases, the application program should implement the
311      * {@link android.security.KeyChainAliasCallback} interface and pass it to
312      * {@link android.security.KeyChain#choosePrivateKeyAlias} to start an
313      * activity for the user to choose the proper alias. The keychain activity will
314      * provide the alias through the callback method in the implemented interface. Next
315      * the application should create an async task to call
316      * {@link android.security.KeyChain#getPrivateKey} to receive the key.
317      *
318      * An example implementation of client certificates can be seen at
319      * <A href="https://android.googlesource.com/platform/packages/apps/Browser/+/android-5.1.1_r1/src/com/android/browser/Tab.java">
320      * AOSP Browser</a>
321      *
322      * The default behavior is to cancel, returning no client certificate.
323      *
324      * @param view The WebView that is initiating the callback
325      * @param request An instance of a {@link ClientCertRequest}
326      *
327      */
onReceivedClientCertRequest(WebView view, ClientCertRequest request)328     public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
329         request.cancel();
330     }
331 
332     /**
333      * Notifies the host application that the WebView received an HTTP
334      * authentication request. The host application can use the supplied
335      * {@link HttpAuthHandler} to set the WebView's response to the request.
336      * The default behavior is to cancel the request.
337      *
338      * @param view the WebView that is initiating the callback
339      * @param handler the HttpAuthHandler used to set the WebView's response
340      * @param host the host requiring authentication
341      * @param realm the realm for which authentication is required
342      * @see WebView#getHttpAuthUsernamePassword
343      */
onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm)344     public void onReceivedHttpAuthRequest(WebView view,
345             HttpAuthHandler handler, String host, String realm) {
346         handler.cancel();
347     }
348 
349     /**
350      * Give the host application a chance to handle the key event synchronously.
351      * e.g. menu shortcut key events need to be filtered this way. If return
352      * true, WebView will not handle the key event. If return false, WebView
353      * will always handle the key event, so none of the super in the view chain
354      * will see the key event. The default behavior returns false.
355      *
356      * @param view The WebView that is initiating the callback.
357      * @param event The key event.
358      * @return True if the host application wants to handle the key event
359      *         itself, otherwise return false
360      */
shouldOverrideKeyEvent(WebView view, KeyEvent event)361     public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
362         return false;
363     }
364 
365     /**
366      * Notify the host application that a key was not handled by the WebView.
367      * Except system keys, WebView always consumes the keys in the normal flow
368      * or if shouldOverrideKeyEvent returns true. This is called asynchronously
369      * from where the key is dispatched. It gives the host application a chance
370      * to handle the unhandled key events.
371      *
372      * @param view The WebView that is initiating the callback.
373      * @param event The key event.
374      * @deprecated This method is subsumed by the more generic onUnhandledInputEvent.
375      */
376     @Deprecated
onUnhandledKeyEvent(WebView view, KeyEvent event)377     public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
378         onUnhandledInputEventInternal(view, event);
379     }
380 
381     /**
382      * Notify the host application that a input event was not handled by the WebView.
383      * Except system keys, WebView always consumes input events in the normal flow
384      * or if shouldOverrideKeyEvent returns true. This is called asynchronously
385      * from where the event is dispatched. It gives the host application a chance
386      * to handle the unhandled input events.
387      *
388      * Note that if the event is a {@link android.view.MotionEvent}, then it's lifetime is only
389      * that of the function call. If the WebViewClient wishes to use the event beyond that, then it
390      * <i>must</i> create a copy of the event.
391      *
392      * It is the responsibility of overriders of this method to call
393      * {@link #onUnhandledKeyEvent(WebView, KeyEvent)}
394      * when appropriate if they wish to continue receiving events through it.
395      *
396      * @param view The WebView that is initiating the callback.
397      * @param event The input event.
398      */
onUnhandledInputEvent(WebView view, InputEvent event)399     public void onUnhandledInputEvent(WebView view, InputEvent event) {
400         if (event instanceof KeyEvent) {
401             onUnhandledKeyEvent(view, (KeyEvent) event);
402             return;
403         }
404         onUnhandledInputEventInternal(view, event);
405     }
406 
onUnhandledInputEventInternal(WebView view, InputEvent event)407     private void onUnhandledInputEventInternal(WebView view, InputEvent event) {
408         ViewRootImpl root = view.getViewRootImpl();
409         if (root != null) {
410             root.dispatchUnhandledInputEvent(event);
411         }
412     }
413 
414     /**
415      * Notify the host application that the scale applied to the WebView has
416      * changed.
417      *
418      * @param view he WebView that is initiating the callback.
419      * @param oldScale The old scale factor
420      * @param newScale The new scale factor
421      */
onScaleChanged(WebView view, float oldScale, float newScale)422     public void onScaleChanged(WebView view, float oldScale, float newScale) {
423     }
424 
425     /**
426      * Notify the host application that a request to automatically log in the
427      * user has been processed.
428      * @param view The WebView requesting the login.
429      * @param realm The account realm used to look up accounts.
430      * @param account An optional account. If not null, the account should be
431      *                checked against accounts on the device. If it is a valid
432      *                account, it should be used to log in the user.
433      * @param args Authenticator specific arguments used to log in the user.
434      */
onReceivedLoginRequest(WebView view, String realm, String account, String args)435     public void onReceivedLoginRequest(WebView view, String realm,
436             String account, String args) {
437     }
438 }
439