WebChromeClient.java revision 451e338c51e8c45efc0d21536dfae6f78f6d5e06
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.annotation.SystemApi;
20import android.content.Intent;
21import android.content.pm.ActivityInfo;
22import android.graphics.Bitmap;
23import android.net.Uri;
24import android.os.Message;
25import android.view.View;
26
27public class WebChromeClient {
28
29    /**
30     * Tell the host application the current progress of loading a page.
31     * @param view The WebView that initiated the callback.
32     * @param newProgress Current page loading progress, represented by
33     *                    an integer between 0 and 100.
34     */
35    public void onProgressChanged(WebView view, int newProgress) {}
36
37    /**
38     * Notify the host application of a change in the document title.
39     * @param view The WebView that initiated the callback.
40     * @param title A String containing the new title of the document.
41     */
42    public void onReceivedTitle(WebView view, String title) {}
43
44    /**
45     * Notify the host application of a new favicon for the current page.
46     * @param view The WebView that initiated the callback.
47     * @param icon A Bitmap containing the favicon for the current page.
48     */
49    public void onReceivedIcon(WebView view, Bitmap icon) {}
50
51    /**
52     * Notify the host application of the url for an apple-touch-icon.
53     * @param view The WebView that initiated the callback.
54     * @param url The icon url.
55     * @param precomposed True if the url is for a precomposed touch icon.
56     */
57    public void onReceivedTouchIconUrl(WebView view, String url,
58            boolean precomposed) {}
59
60    /**
61     * A callback interface used by the host application to notify
62     * the current page that its custom view has been dismissed.
63     */
64    public interface CustomViewCallback {
65        /**
66         * Invoked when the host application dismisses the
67         * custom view.
68         */
69        public void onCustomViewHidden();
70    }
71
72    /**
73     * Notify the host application that the current page would
74     * like to show a custom View.  This is used for Fullscreen
75     * video playback; see "HTML5 Video support" documentation on
76     * {@link WebView}.
77     * @param view is the View object to be shown.
78     * @param callback is the callback to be invoked if and when the view
79     * is dismissed.
80     */
81    public void onShowCustomView(View view, CustomViewCallback callback) {};
82
83    /**
84     * Notify the host application that the current page would
85     * like to show a custom View in a particular orientation.
86     * @param view is the View object to be shown.
87     * @param requestedOrientation An orientation constant as used in
88     * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
89     * @param callback is the callback to be invoked if and when the view
90     * is dismissed.
91     * @deprecated This method supports the obsolete plugin mechanism,
92     * and will not be invoked in future
93     */
94    @Deprecated
95    public void onShowCustomView(View view, int requestedOrientation,
96            CustomViewCallback callback) {};
97
98    /**
99     * Notify the host application that the current page would
100     * like to hide its custom view.
101     */
102    public void onHideCustomView() {}
103
104    /**
105     * Request the host application to create a new window. If the host
106     * application chooses to honor this request, it should return true from
107     * this method, create a new WebView to host the window, insert it into the
108     * View system and send the supplied resultMsg message to its target with
109     * the new WebView as an argument. If the host application chooses not to
110     * honor the request, it should return false from this method. The default
111     * implementation of this method does nothing and hence returns false.
112     * @param view The WebView from which the request for a new window
113     *             originated.
114     * @param isDialog True if the new window should be a dialog, rather than
115     *                 a full-size window.
116     * @param isUserGesture True if the request was initiated by a user gesture,
117     *                      such as the user clicking a link.
118     * @param resultMsg The message to send when once a new WebView has been
119     *                  created. resultMsg.obj is a
120     *                  {@link WebView.WebViewTransport} object. This should be
121     *                  used to transport the new WebView, by calling
122     *                  {@link WebView.WebViewTransport#setWebView(WebView)
123     *                  WebView.WebViewTransport.setWebView(WebView)}.
124     * @return This method should return true if the host application will
125     *         create a new window, in which case resultMsg should be sent to
126     *         its target. Otherwise, this method should return false. Returning
127     *         false from this method but also sending resultMsg will result in
128     *         undefined behavior.
129     */
130    public boolean onCreateWindow(WebView view, boolean isDialog,
131            boolean isUserGesture, Message resultMsg) {
132        return false;
133    }
134
135    /**
136     * Request display and focus for this WebView. This may happen due to
137     * another WebView opening a link in this WebView and requesting that this
138     * WebView be displayed.
139     * @param view The WebView that needs to be focused.
140     */
141    public void onRequestFocus(WebView view) {}
142
143    /**
144     * Notify the host application to close the given WebView and remove it
145     * from the view system if necessary. At this point, WebCore has stopped
146     * any loading in this window and has removed any cross-scripting ability
147     * in javascript.
148     * @param window The WebView that needs to be closed.
149     */
150    public void onCloseWindow(WebView window) {}
151
152    /**
153     * Tell the client to display a javascript alert dialog.  If the client
154     * returns true, WebView will assume that the client will handle the
155     * dialog.  If the client returns false, it will continue execution.
156     * @param view The WebView that initiated the callback.
157     * @param url The url of the page requesting the dialog.
158     * @param message Message to be displayed in the window.
159     * @param result A JsResult to confirm that the user hit enter.
160     * @return boolean Whether the client will handle the alert dialog.
161     */
162    public boolean onJsAlert(WebView view, String url, String message,
163            JsResult result) {
164        return false;
165    }
166
167    /**
168     * Tell the client to display a confirm dialog to the user. If the client
169     * returns true, WebView will assume that the client will handle the
170     * confirm dialog and call the appropriate JsResult method. If the
171     * client returns false, a default value of false will be returned to
172     * javascript. The default behavior is to return false.
173     * @param view The WebView that initiated the callback.
174     * @param url The url of the page requesting the dialog.
175     * @param message Message to be displayed in the window.
176     * @param result A JsResult used to send the user's response to
177     *               javascript.
178     * @return boolean Whether the client will handle the confirm dialog.
179     */
180    public boolean onJsConfirm(WebView view, String url, String message,
181            JsResult result) {
182        return false;
183    }
184
185    /**
186     * Tell the client to display a prompt dialog to the user. If the client
187     * returns true, WebView will assume that the client will handle the
188     * prompt dialog and call the appropriate JsPromptResult method. If the
189     * client returns false, a default value of false will be returned to to
190     * javascript. The default behavior is to return false.
191     * @param view The WebView that initiated the callback.
192     * @param url The url of the page requesting the dialog.
193     * @param message Message to be displayed in the window.
194     * @param defaultValue The default value displayed in the prompt dialog.
195     * @param result A JsPromptResult used to send the user's reponse to
196     *               javascript.
197     * @return boolean Whether the client will handle the prompt dialog.
198     */
199    public boolean onJsPrompt(WebView view, String url, String message,
200            String defaultValue, JsPromptResult result) {
201        return false;
202    }
203
204    /**
205     * Tell the client to display a dialog to confirm navigation away from the
206     * current page. This is the result of the onbeforeunload javascript event.
207     * If the client returns true, WebView will assume that the client will
208     * handle the confirm dialog and call the appropriate JsResult method. If
209     * the client returns false, a default value of true will be returned to
210     * javascript to accept navigation away from the current page. The default
211     * behavior is to return false. Setting the JsResult to true will navigate
212     * away from the current page, false will cancel the navigation.
213     * @param view The WebView that initiated the callback.
214     * @param url The url of the page requesting the dialog.
215     * @param message Message to be displayed in the window.
216     * @param result A JsResult used to send the user's response to
217     *               javascript.
218     * @return boolean Whether the client will handle the confirm dialog.
219     */
220    public boolean onJsBeforeUnload(WebView view, String url, String message,
221            JsResult result) {
222        return false;
223    }
224
225   /**
226    * Tell the client that the quota has been exceeded for the Web SQL Database
227    * API for a particular origin and request a new quota. The client must
228    * respond by invoking the
229    * {@link WebStorage.QuotaUpdater#updateQuota(long) updateQuota(long)}
230    * method of the supplied {@link WebStorage.QuotaUpdater} instance. The
231    * minimum value that can be set for the new quota is the current quota. The
232    * default implementation responds with the current quota, so the quota will
233    * not be increased.
234    * @param url The URL of the page that triggered the notification
235    * @param databaseIdentifier The identifier of the database where the quota
236    *                           was exceeded.
237    * @param quota The quota for the origin, in bytes
238    * @param estimatedDatabaseSize The estimated size of the offending
239    *                              database, in bytes
240    * @param totalQuota The total quota for all origins, in bytes
241    * @param quotaUpdater An instance of {@link WebStorage.QuotaUpdater} which
242    *                     must be used to inform the WebView of the new quota.
243    * @deprecated This method is no longer called; WebView now uses the HTML5 / JavaScript Quota
244    *             Management API.
245    */
246    @Deprecated
247    public void onExceededDatabaseQuota(String url, String databaseIdentifier,
248            long quota, long estimatedDatabaseSize, long totalQuota,
249            WebStorage.QuotaUpdater quotaUpdater) {
250        // This default implementation passes the current quota back to WebCore.
251        // WebCore will interpret this that new quota was declined.
252        quotaUpdater.updateQuota(quota);
253    }
254
255   /**
256    * Notify the host application that the Application Cache has reached the
257    * maximum size. The client must respond by invoking the
258    * {@link WebStorage.QuotaUpdater#updateQuota(long) updateQuota(long)}
259    * method of the supplied {@link WebStorage.QuotaUpdater} instance. The
260    * minimum value that can be set for the new quota is the current quota. The
261    * default implementation responds with the current quota, so the quota will
262    * not be increased.
263    * @param requiredStorage The amount of storage required by the Application
264    *                        Cache operation that triggered this notification,
265    *                        in bytes.
266    * @param quota the current maximum Application Cache size, in bytes
267    * @param quotaUpdater An instance of {@link WebStorage.QuotaUpdater} which
268    *                     must be used to inform the WebView of the new quota.
269    * @deprecated This method is no longer called; WebView now uses the HTML5 / JavaScript Quota
270    *             Management API.
271    */
272    @Deprecated
273    public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
274            WebStorage.QuotaUpdater quotaUpdater) {
275        quotaUpdater.updateQuota(quota);
276    }
277
278    /**
279     * Notify the host application that web content from the specified origin
280     * is attempting to use the Geolocation API, but no permission state is
281     * currently set for that origin. The host application should invoke the
282     * specified callback with the desired permission state. See
283     * {@link GeolocationPermissions} for details.
284     * @param origin The origin of the web content attempting to use the
285     *               Geolocation API.
286     * @param callback The callback to use to set the permission state for the
287     *                 origin.
288     */
289    public void onGeolocationPermissionsShowPrompt(String origin,
290            GeolocationPermissions.Callback callback) {}
291
292    /**
293     * Notify the host application that a request for Geolocation permissions,
294     * made with a previous call to
295     * {@link #onGeolocationPermissionsShowPrompt(String,GeolocationPermissions.Callback) onGeolocationPermissionsShowPrompt()}
296     * has been canceled. Any related UI should therefore be hidden.
297     */
298    public void onGeolocationPermissionsHidePrompt() {}
299
300    /**
301     * Notify the host application that web content is requesting permission to
302     * access the specified resources and the permission currently isn't granted
303     * or denied. The host application must invoke {@link PermissionRequest#grant(String[])}
304     * or {@link PermissionRequest#deny()}.
305     *
306     * If this method isn't overridden, the permission is denied.
307     *
308     * @param request the PermissionRequest from current web content.
309     */
310    public void onPermissionRequest(PermissionRequest request) {
311        request.deny();
312    }
313
314    /**
315     * Notify the host application that the given permission request
316     * has been canceled. Any related UI should therefore be hidden.
317     *
318     * @param request the PermissionRequest that needs be canceled.
319     */
320    public void onPermissionRequestCanceled(PermissionRequest request) {}
321
322    /**
323     * Tell the client that a JavaScript execution timeout has occured. And the
324     * client may decide whether or not to interrupt the execution. If the
325     * client returns true, the JavaScript will be interrupted. If the client
326     * returns false, the execution will continue. Note that in the case of
327     * continuing execution, the timeout counter will be reset, and the callback
328     * will continue to occur if the script does not finish at the next check
329     * point.
330     * @return boolean Whether the JavaScript execution should be interrupted.
331     * @deprecated This method is no longer supported and will not be invoked.
332     */
333    // This method was only called when using the JSC javascript engine. V8 became
334    // the default JS engine with Froyo and support for building with JSC was
335    // removed in b/5495373. V8 does not have a mechanism for making a callback such
336    // as this.
337    public boolean onJsTimeout() {
338        return true;
339    }
340
341    /**
342     * Report a JavaScript error message to the host application. The ChromeClient
343     * should override this to process the log message as they see fit.
344     * @param message The error message to report.
345     * @param lineNumber The line number of the error.
346     * @param sourceID The name of the source file that caused the error.
347     * @deprecated Use {@link #onConsoleMessage(ConsoleMessage) onConsoleMessage(ConsoleMessage)}
348     *      instead.
349     */
350    @Deprecated
351    public void onConsoleMessage(String message, int lineNumber, String sourceID) { }
352
353    /**
354     * Report a JavaScript console message to the host application. The ChromeClient
355     * should override this to process the log message as they see fit.
356     * @param consoleMessage Object containing details of the console message.
357     * @return true if the message is handled by the client.
358     */
359    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
360        // Call the old version of this function for backwards compatability.
361        onConsoleMessage(consoleMessage.message(), consoleMessage.lineNumber(),
362                consoleMessage.sourceId());
363        return false;
364    }
365
366    /**
367     * When not playing, video elements are represented by a 'poster' image. The
368     * image to use can be specified by the poster attribute of the video tag in
369     * HTML. If the attribute is absent, then a default poster will be used. This
370     * method allows the ChromeClient to provide that default image.
371     *
372     * @return Bitmap The image to use as a default poster, or null if no such image is
373     * available.
374     */
375    public Bitmap getDefaultVideoPoster() {
376        return null;
377    }
378
379    /**
380     * When the user starts to playback a video element, it may take time for enough
381     * data to be buffered before the first frames can be rendered. While this buffering
382     * is taking place, the ChromeClient can use this function to provide a View to be
383     * displayed. For example, the ChromeClient could show a spinner animation.
384     *
385     * @return View The View to be displayed whilst the video is loading.
386     */
387    public View getVideoLoadingProgressView() {
388        return null;
389    }
390
391    /** Obtains a list of all visited history items, used for link coloring
392     */
393    public void getVisitedHistory(ValueCallback<String[]> callback) {
394    }
395
396    /**
397     * Tell the client to show a file chooser.
398     *
399     * This is called to handle HTML forms with 'file' input type, in response to the
400     * user pressing the "Select File" button.
401     * To cancel the request, call <code>filePathCallback.onReceiveValue(null)</code> and
402     * return true.
403     *
404     * @param webView The WebView instance that is initiating the request.
405     * @param filePathCallback Invoke this callback to supply the list of paths to files to upload,
406     *                         or NULL to cancel. Must only be called if the
407     *                         <code>showFileChooser</code> implementations returns true.
408     * @param fileChooserParams Describes the mode of file chooser to be opened, and options to be
409     *                          used with it.
410     * @return true if filePathCallback will be invoked, false to use default handling.
411     *
412     * @see FileChooserParams
413     */
414    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
415            FileChooserParams fileChooserParams) {
416        return false;
417    }
418
419    /**
420     * Parameters used in the {@link #onShowFileChooser} method.
421     */
422    public static abstract class FileChooserParams {
423        /** Open single file. Requires that the file exists before allowing the user to pick it. */
424        public static final int MODE_OPEN = 0;
425        /** Like Open but allows multiple files to be selected. */
426        public static final int MODE_OPEN_MULTIPLE = 1;
427        /** Like Open but allows a folder to be selected. The implementation should enumerate
428            all files selected by this operation.
429            This feature is not supported at the moment.
430            @hide */
431        public static final int MODE_OPEN_FOLDER = 2;
432        /**  Allows picking a nonexistent file and saving it. */
433        public static final int MODE_SAVE = 3;
434
435        /**
436         * Parse the result returned by the file picker activity. This method should be used with
437         * {@link #createIntent}. Refer to {@link #createIntent} for how to use it.
438         *
439         * @param resultCode the integer result code returned by the file picker activity.
440         * @param data the intent returned by the file picker activity.
441         * @return the Uris of selected file(s) or null if the resultCode indicates
442         *         activity canceled or any other error.
443         */
444        public static Uri[] parseResult(int resultCode, Intent data) {
445            return WebViewFactory.getProvider().getStatics().parseFileChooserResult(resultCode, data);
446        }
447
448        /**
449         * Returns file chooser mode.
450         */
451        public abstract int getMode();
452
453        /**
454         * Returns an array of acceptable MIME types. The returned MIME type
455         * could be partial such as audio/*. The array will be empty if no
456         * acceptable types are specified.
457         */
458        public abstract String[] getAcceptTypes();
459
460        /**
461         * Returns preference for a live media captured value (e.g. Camera, Microphone).
462         * True indicates capture is enabled, false disabled.
463         *
464         * Use <code>getAcceptTypes</code> to determine suitable capture devices.
465         */
466        public abstract boolean isCaptureEnabled();
467
468        /**
469         * Returns the title to use for this file selector, or null. If null a default
470         * title should be used.
471         */
472        public abstract CharSequence getTitle();
473
474        /**
475         * The file name of a default selection if specified, or null.
476         */
477        public abstract String getFilenameHint();
478
479        /**
480         * Creates an intent that would start a file picker for file selection.
481         * The Intent supports choosing files from simple file sources available
482         * on the device. Some advanced sources (for example, live media capture)
483         * may not be supported and applications wishing to support these sources
484         * or more advanced file operations should build their own Intent.
485         *
486         * <pre>
487         * How to use:
488         * 1. Build an intent using {@link #createIntent}
489         * 2. Fire the intent using {@link android.app.Activity#startActivityForResult}.
490         * 3. Check for ActivityNotFoundException and take a user friendly action if thrown.
491         * 4. Listen the result using {@link android.app.Activity#onActivityResult}
492         * 5. Parse the result using {@link #parseResult} only if media capture was not requested.
493         * 6. Send the result using filePathCallback of {@link WebChromeClient#onShowFileChooser}
494         * </pre>
495         *
496         * @return an Intent that supports basic file chooser sources.
497         */
498        public abstract Intent createIntent();
499    }
500
501    /**
502     * Tell the client to open a file chooser.
503     * @param uploadFile A ValueCallback to set the URI of the file to upload.
504     *      onReceiveValue must be called to wake up the thread.a
505     * @param acceptType The value of the 'accept' attribute of the input tag
506     *         associated with this file picker.
507     * @param capture The value of the 'capture' attribute of the input tag
508     *         associated with this file picker.
509     *
510     * @deprecated Use {@link #showFileChooser} instead.
511     * @hide This method was not published in any SDK version.
512     */
513    @SystemApi
514    @Deprecated
515    public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
516        uploadFile.onReceiveValue(null);
517    }
518
519    /**
520     * Tell the client that the page being viewed has an autofillable
521     * form and the user would like to set a profile up.
522     * @param msg A Message to send once the user has successfully
523     *      set up a profile and to inform the WebTextView it should
524     *      now autofill using that new profile.
525     * @hide
526     */
527    public void setupAutoFill(Message msg) { }
528
529}
530