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