WebViewClient.java revision b3656049777a3cb9257357ff51c78d7b170938f0
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
17package android.webkit;
18
19import android.graphics.Bitmap;
20import android.net.http.SslError;
21import android.os.Message;
22import android.view.InputEvent;
23import android.view.KeyEvent;
24import android.view.ViewRootImpl;
25
26public 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     */
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     */
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     */
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     */
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     */
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
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     */
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
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
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     */
233    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
234        if (request.isForMainFrame()) {
235            onReceivedError(view,
236                    error.getErrorCode(), error.getDescription(), request.getUrl().toString());
237        }
238    }
239
240    /**
241     * Notify the host application that an HTTP error has been received from the server while
242     * loading a resource.  HTTP errors have status codes &gt;= 400.  This callback will be called
243     * for any resource (iframe, image, etc), not just for the main page. Thus, it is recommended to
244     * perform minimum required work in this callback. Note that the content of the server
245     * response may not be provided within the <b>errorResponse</b> parameter.
246     * @param view The WebView that is initiating the callback.
247     * @param request The originating request.
248     * @param errorResponse Information about the error occured.
249     */
250    public void onReceivedHttpError(
251            WebView view, WebResourceRequest request, WebResourceResponseBase errorResponse) {
252    }
253
254    /**
255     * As the host application if the browser should resend data as the
256     * requested page was a result of a POST. The default is to not resend the
257     * data.
258     *
259     * @param view The WebView that is initiating the callback.
260     * @param dontResend The message to send if the browser should not resend
261     * @param resend The message to send if the browser should resend data
262     */
263    public void onFormResubmission(WebView view, Message dontResend,
264            Message resend) {
265        dontResend.sendToTarget();
266    }
267
268    /**
269     * Notify the host application to update its visited links database.
270     *
271     * @param view The WebView that is initiating the callback.
272     * @param url The url being visited.
273     * @param isReload True if this url is being reloaded.
274     */
275    public void doUpdateVisitedHistory(WebView view, String url,
276            boolean isReload) {
277    }
278
279    /**
280     * Notify the host application that an SSL error occurred while loading a
281     * resource. The host application must call either handler.cancel() or
282     * handler.proceed(). Note that the decision may be retained for use in
283     * response to future SSL errors. The default behavior is to cancel the
284     * load.
285     *
286     * @param view The WebView that is initiating the callback.
287     * @param handler An SslErrorHandler object that will handle the user's
288     *            response.
289     * @param error The SSL error object.
290     */
291    public void onReceivedSslError(WebView view, SslErrorHandler handler,
292            SslError error) {
293        handler.cancel();
294    }
295
296    /**
297     * Notify the host application to handle a SSL client certificate
298     * request. The host application is responsible for showing the UI
299     * if desired and providing the keys. There are three ways to
300     * respond: proceed(), cancel() or ignore(). Webview remembers the
301     * response if proceed() or cancel() is called and does not
302     * call onReceivedClientCertRequest() again for the same host and port
303     * pair. Webview does not remember the response if ignore() is called.
304     *
305     * This method is called on the UI thread. During the callback, the
306     * connection is suspended.
307     *
308     * The default behavior is to cancel, returning no client certificate.
309     *
310     * @param view The WebView that is initiating the callback
311     * @param request An instance of a {@link ClientCertRequest}
312     *
313     */
314    public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
315        request.cancel();
316    }
317
318    /**
319     * Notifies the host application that the WebView received an HTTP
320     * authentication request. The host application can use the supplied
321     * {@link HttpAuthHandler} to set the WebView's response to the request.
322     * The default behavior is to cancel the request.
323     *
324     * @param view the WebView that is initiating the callback
325     * @param handler the HttpAuthHandler used to set the WebView's response
326     * @param host the host requiring authentication
327     * @param realm the realm for which authentication is required
328     * @see WebView#getHttpAuthUsernamePassword
329     */
330    public void onReceivedHttpAuthRequest(WebView view,
331            HttpAuthHandler handler, String host, String realm) {
332        handler.cancel();
333    }
334
335    /**
336     * Give the host application a chance to handle the key event synchronously.
337     * e.g. menu shortcut key events need to be filtered this way. If return
338     * true, WebView will not handle the key event. If return false, WebView
339     * will always handle the key event, so none of the super in the view chain
340     * will see the key event. The default behavior returns false.
341     *
342     * @param view The WebView that is initiating the callback.
343     * @param event The key event.
344     * @return True if the host application wants to handle the key event
345     *         itself, otherwise return false
346     */
347    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
348        return false;
349    }
350
351    /**
352     * Notify the host application that a key was not handled by the WebView.
353     * Except system keys, WebView always consumes the keys in the normal flow
354     * or if shouldOverrideKeyEvent returns true. This is called asynchronously
355     * from where the key is dispatched. It gives the host application a chance
356     * to handle the unhandled key events.
357     *
358     * @param view The WebView that is initiating the callback.
359     * @param event The key event.
360     * @deprecated This method is subsumed by the more generic onUnhandledInputEvent.
361     */
362    @Deprecated
363    public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
364        onUnhandledInputEventInternal(view, event);
365    }
366
367    /**
368     * Notify the host application that a input event was not handled by the WebView.
369     * Except system keys, WebView always consumes input events in the normal flow
370     * or if shouldOverrideKeyEvent returns true. This is called asynchronously
371     * from where the event is dispatched. It gives the host application a chance
372     * to handle the unhandled input events.
373     *
374     * Note that if the event is a {@link android.view.MotionEvent}, then it's lifetime is only
375     * that of the function call. If the WebViewClient wishes to use the event beyond that, then it
376     * <i>must</i> create a copy of the event.
377     *
378     * It is the responsibility of overriders of this method to call
379     * {@link #onUnhandledKeyEvent(WebView, KeyEvent)}
380     * when appropriate if they wish to continue receiving events through it.
381     *
382     * @param view The WebView that is initiating the callback.
383     * @param event The input event.
384     */
385    public void onUnhandledInputEvent(WebView view, InputEvent event) {
386        if (event instanceof KeyEvent) {
387            onUnhandledKeyEvent(view, (KeyEvent) event);
388            return;
389        }
390        onUnhandledInputEventInternal(view, event);
391    }
392
393    private void onUnhandledInputEventInternal(WebView view, InputEvent event) {
394        ViewRootImpl root = view.getViewRootImpl();
395        if (root != null) {
396            root.dispatchUnhandledInputEvent(event);
397        }
398    }
399
400    /**
401     * Notify the host application that the scale applied to the WebView has
402     * changed.
403     *
404     * @param view he WebView that is initiating the callback.
405     * @param oldScale The old scale factor
406     * @param newScale The new scale factor
407     */
408    public void onScaleChanged(WebView view, float oldScale, float newScale) {
409    }
410
411    /**
412     * Notify the host application that a request to automatically log in the
413     * user has been processed.
414     * @param view The WebView requesting the login.
415     * @param realm The account realm used to look up accounts.
416     * @param account An optional account. If not null, the account should be
417     *                checked against accounts on the device. If it is a valid
418     *                account, it should be used to log in the user.
419     * @param args Authenticator specific arguments used to log in the user.
420     */
421    public void onReceivedLoginRequest(WebView view, String realm,
422            String account, String args) {
423    }
424}
425