cordova-plugin-inappbrowser-patch 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CONTRIBUTING.md +37 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +722 -0
  5. package/RELEASENOTES.md +801 -0
  6. package/package.json +60 -0
  7. package/plugin.xml +103 -0
  8. package/src/android/InAppBrowser.java +1503 -0
  9. package/src/android/InAppBrowserDialog.java +57 -0
  10. package/src/android/InAppChromeClient.java +190 -0
  11. package/src/android/res/drawable-hdpi/ic_action_next_item.png +0 -0
  12. package/src/android/res/drawable-hdpi/ic_action_previous_item.png +0 -0
  13. package/src/android/res/drawable-hdpi/ic_action_remove.png +0 -0
  14. package/src/android/res/drawable-mdpi/ic_action_next_item.png +0 -0
  15. package/src/android/res/drawable-mdpi/ic_action_previous_item.png +0 -0
  16. package/src/android/res/drawable-mdpi/ic_action_remove.png +0 -0
  17. package/src/android/res/drawable-xhdpi/ic_action_next_item.png +0 -0
  18. package/src/android/res/drawable-xhdpi/ic_action_previous_item.png +0 -0
  19. package/src/android/res/drawable-xhdpi/ic_action_remove.png +0 -0
  20. package/src/android/res/drawable-xxhdpi/ic_action_next_item.png +0 -0
  21. package/src/android/res/drawable-xxhdpi/ic_action_previous_item.png +0 -0
  22. package/src/android/res/drawable-xxhdpi/ic_action_remove.png +0 -0
  23. package/src/browser/InAppBrowserProxy.js +245 -0
  24. package/src/ios/CDVInAppBrowserNavigationController.h +28 -0
  25. package/src/ios/CDVInAppBrowserNavigationController.m +63 -0
  26. package/src/ios/CDVInAppBrowserOptions.h +51 -0
  27. package/src/ios/CDVInAppBrowserOptions.m +90 -0
  28. package/src/ios/CDVWKInAppBrowser.h +80 -0
  29. package/src/ios/CDVWKInAppBrowser.m +1223 -0
  30. package/src/ios/CDVWKInAppBrowserUIDelegate.h +32 -0
  31. package/src/ios/CDVWKInAppBrowserUIDelegate.m +127 -0
  32. package/types/index.d.ts +109 -0
  33. package/www/inappbrowser.js +124 -0
@@ -0,0 +1,1503 @@
1
+ /*
2
+ Licensed to the Apache Software Foundation (ASF) under one
3
+ or more contributor license agreements. See the NOTICE file
4
+ distributed with this work for additional information
5
+ regarding copyright ownership. The ASF licenses this file
6
+ to you under the Apache License, Version 2.0 (the
7
+ "License"); you may not use this file except in compliance
8
+ with the License. You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing,
13
+ software distributed under the License is distributed on an
14
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ KIND, either express or implied. See the License for the
16
+ specific language governing permissions and limitations
17
+ under the License.
18
+ */
19
+ package org.apache.cordova.inappbrowser;
20
+
21
+ import android.annotation.SuppressLint;
22
+ import android.annotation.TargetApi;
23
+ import android.content.Context;
24
+ import android.content.Intent;
25
+ import android.content.pm.PackageManager;
26
+ import android.content.pm.ResolveInfo;
27
+ import android.os.Parcelable;
28
+ import android.provider.Browser;
29
+ import android.content.res.Resources;
30
+ import android.graphics.Bitmap;
31
+ import android.graphics.drawable.Drawable;
32
+ import android.graphics.Color;
33
+ import android.net.http.SslError;
34
+ import android.net.Uri;
35
+ import android.os.Build;
36
+ import android.os.Bundle;
37
+ import android.text.InputType;
38
+ import android.util.TypedValue;
39
+ import android.view.Gravity;
40
+ import android.view.KeyEvent;
41
+ import android.view.View;
42
+ import android.view.Window;
43
+ import android.view.WindowManager;
44
+ import android.view.WindowManager.LayoutParams;
45
+ import android.view.inputmethod.EditorInfo;
46
+ import android.view.inputmethod.InputMethodManager;
47
+ import android.webkit.CookieManager;
48
+ import android.webkit.HttpAuthHandler;
49
+ import android.webkit.JavascriptInterface;
50
+ import android.webkit.SslErrorHandler;
51
+ import android.webkit.ValueCallback;
52
+ import android.webkit.WebChromeClient;
53
+ import android.webkit.WebResourceRequest;
54
+ import android.webkit.WebResourceResponse;
55
+ import android.webkit.WebSettings;
56
+ import android.webkit.WebView;
57
+ import android.webkit.DownloadListener;
58
+ import android.webkit.WebViewClient;
59
+ import android.widget.EditText;
60
+ import android.widget.ImageButton;
61
+ import android.widget.ImageView;
62
+ import android.widget.LinearLayout;
63
+ import android.widget.RelativeLayout;
64
+ import android.widget.TextView;
65
+
66
+ import org.apache.cordova.CallbackContext;
67
+ import org.apache.cordova.Config;
68
+ import org.apache.cordova.CordovaArgs;
69
+ import org.apache.cordova.CordovaHttpAuthHandler;
70
+ import org.apache.cordova.CordovaPlugin;
71
+ import org.apache.cordova.CordovaWebView;
72
+ import org.apache.cordova.LOG;
73
+ import org.apache.cordova.PluginManager;
74
+ import org.apache.cordova.PluginResult;
75
+ import org.json.JSONException;
76
+ import org.json.JSONObject;
77
+
78
+ import java.lang.reflect.InvocationTargetException;
79
+ import java.lang.reflect.Field;
80
+ import java.lang.reflect.Method;
81
+ import java.util.ArrayList;
82
+ import java.util.Arrays;
83
+ import java.util.List;
84
+ import java.util.HashMap;
85
+ import java.util.StringTokenizer;
86
+
87
+ @SuppressLint("SetJavaScriptEnabled")
88
+ public class InAppBrowser extends CordovaPlugin {
89
+
90
+ private static final String NULL = "null";
91
+ protected static final String LOG_TAG = "InAppBrowser";
92
+ private static final String SELF = "_self";
93
+ private static final String SYSTEM = "_system";
94
+ private static final String EXIT_EVENT = "exit";
95
+ private static final String LOCATION = "location";
96
+ private static final String ZOOM = "zoom";
97
+ private static final String HIDDEN = "hidden";
98
+ private static final String LOAD_START_EVENT = "loadstart";
99
+ private static final String LOAD_STOP_EVENT = "loadstop";
100
+ private static final String LOAD_ERROR_EVENT = "loaderror";
101
+ private static final String DOWNLOAD_EVENT = "download";
102
+ private static final String MESSAGE_EVENT = "message";
103
+ private static final String CLEAR_ALL_CACHE = "clearcache";
104
+ private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
105
+ private static final String HARDWARE_BACK_BUTTON = "hardwareback";
106
+ private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
107
+ private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
108
+ private static final Boolean DEFAULT_HARDWARE_BACK = true;
109
+ private static final String USER_WIDE_VIEW_PORT = "useWideViewPort";
110
+ private static final String TOOLBAR_COLOR = "toolbarcolor";
111
+ private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
112
+ private static final String CLOSE_BUTTON_COLOR = "closebuttoncolor";
113
+ private static final String LEFT_TO_RIGHT = "lefttoright";
114
+ private static final String HIDE_NAVIGATION = "hidenavigationbuttons";
115
+ private static final String NAVIGATION_COLOR = "navigationbuttoncolor";
116
+ private static final String HIDE_URL = "hideurlbar";
117
+ private static final String FOOTER = "footer";
118
+ private static final String FOOTER_COLOR = "footercolor";
119
+ private static final String BEFORELOAD = "beforeload";
120
+ private static final String FULLSCREEN = "fullscreen";
121
+ private static final String LAUNCH_NEW_TASK = "launchInNewTask";
122
+
123
+ private static final int TOOLBAR_HEIGHT = 48;
124
+
125
+ private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR);
126
+
127
+ private InAppBrowserDialog dialog;
128
+ private WebView inAppWebView;
129
+ private EditText edittext;
130
+ private CallbackContext callbackContext;
131
+ private boolean showLocationBar = true;
132
+ private boolean showZoomControls = true;
133
+ private boolean openWindowHidden = false;
134
+ private boolean clearAllCache = false;
135
+ private boolean clearSessionCache = false;
136
+ private boolean hadwareBackButton = true;
137
+ private boolean mediaPlaybackRequiresUserGesture = false;
138
+ private boolean shouldPauseInAppBrowser = false;
139
+ private boolean useWideViewPort = true;
140
+ private ValueCallback<Uri[]> mUploadCallback;
141
+ private final static int FILECHOOSER_REQUESTCODE = 1;
142
+ private String closeButtonCaption = "";
143
+ private String closeButtonColor = "";
144
+ private boolean leftToRight = false;
145
+ private int toolbarColor = android.graphics.Color.LTGRAY;
146
+ private boolean hideNavigationButtons = false;
147
+ private String navigationButtonColor = "";
148
+ private boolean hideUrlBar = false;
149
+ private boolean showFooter = false;
150
+ private String footerColor = "";
151
+ private String beforeload = "";
152
+ private boolean fullscreen = true;
153
+ private boolean launchInNewTask = false;
154
+ private String[] allowedSchemes;
155
+ private InAppBrowserClient currentClient;
156
+
157
+ /**
158
+ * Executes the request and returns PluginResult.
159
+ *
160
+ * @param action the action to execute.
161
+ * @param args JSONArry of arguments for the plugin.
162
+ * @param callbackContext the callbackContext used when calling back into JavaScript.
163
+ * @return A PluginResult object with a status and message.
164
+ */
165
+ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
166
+ if (action.equals("open")) {
167
+ this.callbackContext = callbackContext;
168
+ final String url = args.getString(0);
169
+ String t = args.optString(1);
170
+ if (t == null || t.equals("") || t.equals(NULL)) {
171
+ t = SELF;
172
+ }
173
+ final String target = t;
174
+ final HashMap<String, String> features = parseFeature(args.optString(2));
175
+
176
+ LOG.d(LOG_TAG, "target = " + target);
177
+
178
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
179
+ @Override
180
+ public void run() {
181
+ String result = "";
182
+ // SELF
183
+ if (SELF.equals(target)) {
184
+ LOG.d(LOG_TAG, "in self");
185
+ /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
186
+ * Previously the Config class had a static method, isUrlWhitelisted(). That
187
+ * responsibility has been moved to the plugins, with an aggregating method in
188
+ * PluginManager.
189
+ */
190
+ Boolean shouldAllowNavigation = null;
191
+ if (url.startsWith("javascript:")) {
192
+ shouldAllowNavigation = true;
193
+ }
194
+ if (shouldAllowNavigation == null) {
195
+ try {
196
+ Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
197
+ shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
198
+ } catch (NoSuchMethodException e) {
199
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
200
+ } catch (IllegalAccessException e) {
201
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
202
+ } catch (InvocationTargetException e) {
203
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
204
+ }
205
+ }
206
+ if (shouldAllowNavigation == null) {
207
+ try {
208
+ Method gpm = webView.getClass().getMethod("getPluginManager");
209
+ PluginManager pm = (PluginManager)gpm.invoke(webView);
210
+ Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
211
+ shouldAllowNavigation = (Boolean)san.invoke(pm, url);
212
+ } catch (NoSuchMethodException e) {
213
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
214
+ } catch (IllegalAccessException e) {
215
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
216
+ } catch (InvocationTargetException e) {
217
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
218
+ }
219
+ }
220
+ // load in webview
221
+ if (Boolean.TRUE.equals(shouldAllowNavigation)) {
222
+ LOG.d(LOG_TAG, "loading in webview");
223
+ webView.loadUrl(url);
224
+ }
225
+ //Load the dialer
226
+ else if (url.startsWith(WebView.SCHEME_TEL))
227
+ {
228
+ try {
229
+ LOG.d(LOG_TAG, "loading in dialer");
230
+ Intent intent = new Intent(Intent.ACTION_DIAL);
231
+ intent.setData(Uri.parse(url));
232
+ cordova.getActivity().startActivity(intent);
233
+ } catch (android.content.ActivityNotFoundException e) {
234
+ LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
235
+ }
236
+ }
237
+ // load in InAppBrowser
238
+ else {
239
+ LOG.d(LOG_TAG, "loading in InAppBrowser");
240
+ result = showWebPage(url, features);
241
+ }
242
+ }
243
+ // SYSTEM
244
+ else if (SYSTEM.equals(target)) {
245
+ LOG.d(LOG_TAG, "in system");
246
+ result = openExternal(url, features);
247
+ }
248
+ // BLANK - or anything else
249
+ else {
250
+ LOG.d(LOG_TAG, "in blank");
251
+ result = showWebPage(url, features);
252
+ }
253
+
254
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
255
+ pluginResult.setKeepCallback(true);
256
+ callbackContext.sendPluginResult(pluginResult);
257
+ }
258
+ });
259
+ }
260
+ else if (action.equals("close")) {
261
+ closeDialog();
262
+ }
263
+ else if (action.equals("loadAfterBeforeload")) {
264
+ if (beforeload == null) {
265
+ LOG.e(LOG_TAG, "unexpected loadAfterBeforeload called without feature beforeload=yes");
266
+ }
267
+ final String url = args.getString(0);
268
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
269
+ @SuppressLint("NewApi")
270
+ @Override
271
+ public void run() {
272
+ if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
273
+ currentClient.waitForBeforeload = false;
274
+ inAppWebView.setWebViewClient(currentClient);
275
+ } else {
276
+ ((InAppBrowserClient)inAppWebView.getWebViewClient()).waitForBeforeload = false;
277
+ }
278
+ inAppWebView.loadUrl(url);
279
+
280
+ }
281
+ });
282
+ }
283
+ else if (action.equals("injectScriptCode")) {
284
+ String jsWrapper = null;
285
+ if (args.getBoolean(1)) {
286
+ jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
287
+ }
288
+ injectDeferredObject(args.getString(0), jsWrapper);
289
+ }
290
+ else if (action.equals("injectScriptFile")) {
291
+ String jsWrapper;
292
+ if (args.getBoolean(1)) {
293
+ jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
294
+ } else {
295
+ jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
296
+ }
297
+ injectDeferredObject(args.getString(0), jsWrapper);
298
+ }
299
+ else if (action.equals("injectStyleCode")) {
300
+ String jsWrapper;
301
+ if (args.getBoolean(1)) {
302
+ jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
303
+ } else {
304
+ jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
305
+ }
306
+ injectDeferredObject(args.getString(0), jsWrapper);
307
+ }
308
+ else if (action.equals("injectStyleFile")) {
309
+ String jsWrapper;
310
+ if (args.getBoolean(1)) {
311
+ jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
312
+ } else {
313
+ jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
314
+ }
315
+ injectDeferredObject(args.getString(0), jsWrapper);
316
+ }
317
+ else if (action.equals("show")) {
318
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
319
+ @Override
320
+ public void run() {
321
+ if (dialog != null && !cordova.getActivity().isFinishing()) {
322
+ dialog.show();
323
+ }
324
+ }
325
+ });
326
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
327
+ pluginResult.setKeepCallback(true);
328
+ this.callbackContext.sendPluginResult(pluginResult);
329
+ }
330
+ else if (action.equals("hide")) {
331
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
332
+ @Override
333
+ public void run() {
334
+ if (dialog != null && !cordova.getActivity().isFinishing()) {
335
+ dialog.hide();
336
+ }
337
+ }
338
+ });
339
+ PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
340
+ pluginResult.setKeepCallback(true);
341
+ this.callbackContext.sendPluginResult(pluginResult);
342
+ }
343
+ else {
344
+ return false;
345
+ }
346
+ return true;
347
+ }
348
+
349
+ /**
350
+ * Called when the view navigates.
351
+ */
352
+ @Override
353
+ public void onReset() {
354
+ closeDialog();
355
+ }
356
+
357
+ /**
358
+ * Called when the system is about to start resuming a previous activity.
359
+ */
360
+ @Override
361
+ public void onPause(boolean multitasking) {
362
+ if (shouldPauseInAppBrowser) {
363
+ inAppWebView.onPause();
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Called when the activity will start interacting with the user.
369
+ */
370
+ @Override
371
+ public void onResume(boolean multitasking) {
372
+ if (shouldPauseInAppBrowser) {
373
+ inAppWebView.onResume();
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Called by AccelBroker when listener is to be shut down.
379
+ * Stop listener.
380
+ */
381
+ public void onDestroy() {
382
+ closeDialog();
383
+ }
384
+
385
+ /**
386
+ * Inject an object (script or style) into the InAppBrowser WebView.
387
+ *
388
+ * This is a helper method for the inject{Script|Style}{Code|File} API calls, which
389
+ * provides a consistent method for injecting JavaScript code into the document.
390
+ *
391
+ * If a wrapper string is supplied, then the source string will be JSON-encoded (adding
392
+ * quotes) and wrapped using string formatting. (The wrapper string should have a single
393
+ * '%s' marker)
394
+ *
395
+ * @param source The source object (filename or script/style text) to inject into
396
+ * the document.
397
+ * @param jsWrapper A JavaScript string to wrap the source string in, so that the object
398
+ * is properly injected, or null if the source string is JavaScript text
399
+ * which should be executed directly.
400
+ */
401
+ private void injectDeferredObject(String source, String jsWrapper) {
402
+ if (inAppWebView!=null) {
403
+ String scriptToInject;
404
+ if (jsWrapper != null) {
405
+ org.json.JSONArray jsonEsc = new org.json.JSONArray();
406
+ jsonEsc.put(source);
407
+ String jsonRepr = jsonEsc.toString();
408
+ String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
409
+ scriptToInject = String.format(jsWrapper, jsonSourceString);
410
+ } else {
411
+ scriptToInject = source;
412
+ }
413
+ final String finalScriptToInject = scriptToInject;
414
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
415
+ @SuppressLint("NewApi")
416
+ @Override
417
+ public void run() {
418
+ inAppWebView.evaluateJavascript(finalScriptToInject, null);
419
+ }
420
+ });
421
+ } else {
422
+ LOG.d(LOG_TAG, "Can't inject code into the system browser");
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Put the list of features into a hash map
428
+ *
429
+ * @param optString
430
+ * @return
431
+ */
432
+ private HashMap<String, String> parseFeature(String optString) {
433
+ if (optString.equals(NULL)) {
434
+ return null;
435
+ } else {
436
+ HashMap<String, String> map = new HashMap<String, String>();
437
+ StringTokenizer features = new StringTokenizer(optString, ",");
438
+ StringTokenizer option;
439
+ while(features.hasMoreElements()) {
440
+ option = new StringTokenizer(features.nextToken(), "=");
441
+ if (option.hasMoreElements()) {
442
+ String key = option.nextToken();
443
+ String value = option.nextToken();
444
+ if (!customizableOptions.contains(key)) {
445
+ value = value.equals("yes") || value.equals("no") ? value : "yes";
446
+ }
447
+ map.put(key, value);
448
+ }
449
+ }
450
+ return map;
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Display a new browser with the specified URL.
456
+ *
457
+ * @param url the url to load.
458
+ * @return "" if ok, or error message.
459
+ */
460
+ public String openExternal(String url, HashMap<String, String> features) {
461
+ try {
462
+ Intent intent = null;
463
+ intent = new Intent(Intent.ACTION_VIEW);
464
+ // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
465
+ // Adding the MIME type to http: URLs causes them to not be handled by the downloader.
466
+ Uri uri = Uri.parse(url);
467
+ if ("file".equals(uri.getScheme())) {
468
+ intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
469
+ } else {
470
+ intent.setData(uri);
471
+ }
472
+ intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
473
+
474
+ if (features != null) {
475
+ String launchNewTask = features.get(LAUNCH_NEW_TASK);
476
+ if (launchNewTask != null) {
477
+ launchInNewTask = launchNewTask.equals("yes") ? true : false;
478
+ }
479
+ }
480
+
481
+ if (launchInNewTask) {
482
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
483
+ }
484
+ // CB-10795: Avoid circular loops by preventing it from opening in the current app
485
+ this.openExternalExcludeCurrentApp(intent);
486
+ return "";
487
+ // not catching FileUriExposedException explicitly because buildtools<24 doesn't know about it
488
+ } catch (java.lang.RuntimeException e) {
489
+ LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
490
+ return e.toString();
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Opens the intent, providing a chooser that excludes the current app to avoid
496
+ * circular loops.
497
+ */
498
+ private void openExternalExcludeCurrentApp(Intent intent) {
499
+ String currentPackage = cordova.getActivity().getPackageName();
500
+ boolean hasCurrentPackage = false;
501
+
502
+ PackageManager pm = cordova.getActivity().getPackageManager();
503
+ List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
504
+ ArrayList<Intent> targetIntents = new ArrayList<Intent>();
505
+
506
+ for (ResolveInfo ri : activities) {
507
+ if (!currentPackage.equals(ri.activityInfo.packageName)) {
508
+ Intent targetIntent = (Intent)intent.clone();
509
+ targetIntent.setPackage(ri.activityInfo.packageName);
510
+ targetIntents.add(targetIntent);
511
+ }
512
+ else {
513
+ hasCurrentPackage = true;
514
+ }
515
+ }
516
+
517
+ // If the current app package isn't a target for this URL, then use
518
+ // the normal launch behavior
519
+ if (hasCurrentPackage == false || targetIntents.size() == 0) {
520
+ this.cordova.getActivity().startActivity(intent);
521
+ }
522
+ // If there's only one possible intent, launch it directly
523
+ else if (targetIntents.size() == 1) {
524
+ this.cordova.getActivity().startActivity(targetIntents.get(0));
525
+ }
526
+ // Otherwise, show a custom chooser without the current app listed
527
+ else if (targetIntents.size() > 0) {
528
+ Intent chooser = Intent.createChooser(targetIntents.remove(targetIntents.size()-1), null);
529
+ chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[] {}));
530
+ this.cordova.getActivity().startActivity(chooser);
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Closes the dialog
536
+ */
537
+ public void closeDialog() {
538
+ this.cordova.getActivity().runOnUiThread(new Runnable() {
539
+ @Override
540
+ public void run() {
541
+ final WebView childView = inAppWebView;
542
+ // The JS protects against multiple calls, so this should happen only when
543
+ // closeDialog() is called by other native code.
544
+ if (childView == null) {
545
+ return;
546
+ }
547
+
548
+ childView.setWebViewClient(new WebViewClient() {
549
+ // NB: wait for about:blank before dismissing
550
+ public void onPageFinished(WebView view, String url) {
551
+ if (dialog != null && !cordova.getActivity().isFinishing()) {
552
+ dialog.dismiss();
553
+ dialog = null;
554
+ }
555
+ }
556
+ });
557
+ // NB: From SDK 19: "If you call methods on WebView from any thread
558
+ // other than your app's UI thread, it can cause unexpected results."
559
+ // http://developer.android.com/guide/webapps/migrating.html#Threads
560
+ childView.loadUrl("about:blank");
561
+
562
+ try {
563
+ JSONObject obj = new JSONObject();
564
+ obj.put("type", EXIT_EVENT);
565
+ sendUpdate(obj, false);
566
+ } catch (JSONException ex) {
567
+ LOG.d(LOG_TAG, "Should never happen");
568
+ }
569
+ }
570
+ });
571
+ }
572
+
573
+ /**
574
+ * Checks to see if it is possible to go back one page in history, then does so.
575
+ */
576
+ public void goBack() {
577
+ if (this.inAppWebView.canGoBack()) {
578
+ this.inAppWebView.goBack();
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Can the web browser go back?
584
+ * @return boolean
585
+ */
586
+ public boolean canGoBack() {
587
+ return this.inAppWebView.canGoBack();
588
+ }
589
+
590
+ /**
591
+ * Has the user set the hardware back button to go back
592
+ * @return boolean
593
+ */
594
+ public boolean hardwareBack() {
595
+ return hadwareBackButton;
596
+ }
597
+
598
+ /**
599
+ * Checks to see if it is possible to go forward one page in history, then does so.
600
+ */
601
+ private void goForward() {
602
+ if (this.inAppWebView.canGoForward()) {
603
+ this.inAppWebView.goForward();
604
+ }
605
+ }
606
+
607
+ /**
608
+ * Navigate to the new page
609
+ *
610
+ * @param url to load
611
+ */
612
+ private void navigate(String url) {
613
+ InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
614
+ imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
615
+
616
+ if (!url.startsWith("http") && !url.startsWith("file:")) {
617
+ this.inAppWebView.loadUrl("http://" + url);
618
+ } else {
619
+ this.inAppWebView.loadUrl(url);
620
+ }
621
+ this.inAppWebView.requestFocus();
622
+ }
623
+
624
+
625
+ /**
626
+ * Should we show the location bar?
627
+ *
628
+ * @return boolean
629
+ */
630
+ private boolean getShowLocationBar() {
631
+ return this.showLocationBar;
632
+ }
633
+
634
+ private InAppBrowser getInAppBrowser() {
635
+ return this;
636
+ }
637
+
638
+ /**
639
+ * Display a new browser with the specified URL.
640
+ *
641
+ * @param url the url to load.
642
+ * @param features jsonObject
643
+ */
644
+ public String showWebPage(final String url, HashMap<String, String> features) {
645
+ // Determine if we should hide the location bar.
646
+ showLocationBar = true;
647
+ showZoomControls = true;
648
+ openWindowHidden = false;
649
+ mediaPlaybackRequiresUserGesture = false;
650
+
651
+ if (features != null) {
652
+ String show = features.get(LOCATION);
653
+ if (show != null) {
654
+ showLocationBar = show.equals("yes") ? true : false;
655
+ }
656
+ if(showLocationBar) {
657
+ String hideNavigation = features.get(HIDE_NAVIGATION);
658
+ String hideUrl = features.get(HIDE_URL);
659
+ if(hideNavigation != null) hideNavigationButtons = hideNavigation.equals("yes") ? true : false;
660
+ if(hideUrl != null) hideUrlBar = hideUrl.equals("yes") ? true : false;
661
+ }
662
+ String zoom = features.get(ZOOM);
663
+ if (zoom != null) {
664
+ showZoomControls = zoom.equals("yes") ? true : false;
665
+ }
666
+ String hidden = features.get(HIDDEN);
667
+ if (hidden != null) {
668
+ openWindowHidden = hidden.equals("yes") ? true : false;
669
+ }
670
+ String hardwareBack = features.get(HARDWARE_BACK_BUTTON);
671
+ if (hardwareBack != null) {
672
+ hadwareBackButton = hardwareBack.equals("yes") ? true : false;
673
+ } else {
674
+ hadwareBackButton = DEFAULT_HARDWARE_BACK;
675
+ }
676
+ String mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
677
+ if (mediaPlayback != null) {
678
+ mediaPlaybackRequiresUserGesture = mediaPlayback.equals("yes") ? true : false;
679
+ }
680
+ String cache = features.get(CLEAR_ALL_CACHE);
681
+ if (cache != null) {
682
+ clearAllCache = cache.equals("yes") ? true : false;
683
+ } else {
684
+ cache = features.get(CLEAR_SESSION_CACHE);
685
+ if (cache != null) {
686
+ clearSessionCache = cache.equals("yes") ? true : false;
687
+ }
688
+ }
689
+ String shouldPause = features.get(SHOULD_PAUSE);
690
+ if (shouldPause != null) {
691
+ shouldPauseInAppBrowser = shouldPause.equals("yes") ? true : false;
692
+ }
693
+ String wideViewPort = features.get(USER_WIDE_VIEW_PORT);
694
+ if (wideViewPort != null ) {
695
+ useWideViewPort = wideViewPort.equals("yes") ? true : false;
696
+ }
697
+ String closeButtonCaptionSet = features.get(CLOSE_BUTTON_CAPTION);
698
+ if (closeButtonCaptionSet != null) {
699
+ closeButtonCaption = closeButtonCaptionSet;
700
+ }
701
+ String closeButtonColorSet = features.get(CLOSE_BUTTON_COLOR);
702
+ if (closeButtonColorSet != null) {
703
+ closeButtonColor = closeButtonColorSet;
704
+ }
705
+ String leftToRightSet = features.get(LEFT_TO_RIGHT);
706
+ leftToRight = leftToRightSet != null && leftToRightSet.equals("yes");
707
+
708
+ String toolbarColorSet = features.get(TOOLBAR_COLOR);
709
+ if (toolbarColorSet != null) {
710
+ toolbarColor = android.graphics.Color.parseColor(toolbarColorSet);
711
+ }
712
+ String navigationButtonColorSet = features.get(NAVIGATION_COLOR);
713
+ if (navigationButtonColorSet != null) {
714
+ navigationButtonColor = navigationButtonColorSet;
715
+ }
716
+ String showFooterSet = features.get(FOOTER);
717
+ if (showFooterSet != null) {
718
+ showFooter = showFooterSet.equals("yes") ? true : false;
719
+ }
720
+ String footerColorSet = features.get(FOOTER_COLOR);
721
+ if (footerColorSet != null) {
722
+ footerColor = footerColorSet;
723
+ }
724
+ if (features.get(BEFORELOAD) != null) {
725
+ beforeload = features.get(BEFORELOAD);
726
+ }
727
+ String fullscreenSet = features.get(FULLSCREEN);
728
+ if (fullscreenSet != null) {
729
+ fullscreen = fullscreenSet.equals("yes") ? true : false;
730
+ }
731
+ }
732
+
733
+ final CordovaWebView thatWebView = this.webView;
734
+
735
+ // Create dialog in new thread
736
+ Runnable runnable = new Runnable() {
737
+ /**
738
+ * Convert our DIP units to Pixels
739
+ *
740
+ * @return int
741
+ */
742
+ private int dpToPixels(int dipValue) {
743
+ int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
744
+ (float) dipValue,
745
+ cordova.getActivity().getResources().getDisplayMetrics()
746
+ );
747
+
748
+ return value;
749
+ }
750
+
751
+ private View createCloseButton(int id) {
752
+ View _close;
753
+ Resources activityRes = cordova.getActivity().getResources();
754
+
755
+ if (closeButtonCaption != "") {
756
+ // Use TextView for text
757
+ TextView close = new TextView(cordova.getActivity());
758
+ close.setText(closeButtonCaption);
759
+ close.setTextSize(20);
760
+ if (closeButtonColor != "") close.setTextColor(android.graphics.Color.parseColor(closeButtonColor));
761
+ close.setGravity(android.view.Gravity.CENTER_VERTICAL);
762
+ close.setPadding(this.dpToPixels(10), 0, this.dpToPixels(10), 0);
763
+ _close = close;
764
+ }
765
+ else {
766
+ ImageButton close = new ImageButton(cordova.getActivity());
767
+ int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
768
+ Drawable closeIcon = activityRes.getDrawable(closeResId);
769
+ if (closeButtonColor != "") close.setColorFilter(android.graphics.Color.parseColor(closeButtonColor));
770
+ close.setImageDrawable(closeIcon);
771
+ close.setScaleType(ImageView.ScaleType.FIT_CENTER);
772
+ close.getAdjustViewBounds();
773
+
774
+ _close = close;
775
+ }
776
+
777
+ RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
778
+ if (leftToRight) closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
779
+ else closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
780
+ _close.setLayoutParams(closeLayoutParams);
781
+ _close.setBackground(null);
782
+
783
+ _close.setContentDescription("Close Button");
784
+ _close.setId(Integer.valueOf(id));
785
+ _close.setOnClickListener(new View.OnClickListener() {
786
+ public void onClick(View v) {
787
+ closeDialog();
788
+ }
789
+ });
790
+
791
+ return _close;
792
+ }
793
+
794
+ @SuppressLint("NewApi")
795
+ public void run() {
796
+
797
+ // CB-6702 InAppBrowser hangs when opening more than one instance
798
+ if (dialog != null) {
799
+ dialog.dismiss();
800
+ };
801
+
802
+ // Let's create the main dialog
803
+ dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
804
+ dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
805
+ dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
806
+ if (fullscreen) {
807
+ dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
808
+ }
809
+ dialog.setCancelable(true);
810
+ dialog.setInAppBroswer(getInAppBrowser());
811
+
812
+ // Main container layout
813
+ LinearLayout main = new LinearLayout(cordova.getActivity());
814
+ main.setOrientation(LinearLayout.VERTICAL);
815
+
816
+ // Toolbar layout
817
+ RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
818
+ //Please, no more black!
819
+ toolbar.setBackgroundColor(toolbarColor);
820
+ toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(TOOLBAR_HEIGHT)));
821
+ toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
822
+ if (leftToRight) {
823
+ toolbar.setHorizontalGravity(Gravity.LEFT);
824
+ } else {
825
+ toolbar.setHorizontalGravity(Gravity.RIGHT);
826
+ }
827
+ toolbar.setVerticalGravity(Gravity.TOP);
828
+
829
+ // Action Button Container layout
830
+ RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
831
+ RelativeLayout.LayoutParams actionButtonLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
832
+ if (leftToRight) actionButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
833
+ else actionButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
834
+ actionButtonContainer.setLayoutParams(actionButtonLayoutParams);
835
+ actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
836
+ actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
837
+ actionButtonContainer.setId(leftToRight ? Integer.valueOf(5) : Integer.valueOf(1));
838
+
839
+ // Back button
840
+ ImageButton back = new ImageButton(cordova.getActivity());
841
+ RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
842
+ backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
843
+ back.setLayoutParams(backLayoutParams);
844
+ back.setContentDescription("Back Button");
845
+ back.setId(Integer.valueOf(2));
846
+ Resources activityRes = cordova.getActivity().getResources();
847
+ int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
848
+ Drawable backIcon = activityRes.getDrawable(backResId);
849
+ if (navigationButtonColor != "") back.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
850
+ back.setBackground(null);
851
+ back.setImageDrawable(backIcon);
852
+ back.setScaleType(ImageView.ScaleType.FIT_CENTER);
853
+ back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
854
+ back.getAdjustViewBounds();
855
+
856
+ back.setOnClickListener(new View.OnClickListener() {
857
+ public void onClick(View v) {
858
+ goBack();
859
+ }
860
+ });
861
+
862
+ // Forward button
863
+ ImageButton forward = new ImageButton(cordova.getActivity());
864
+ RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
865
+ forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
866
+ forward.setLayoutParams(forwardLayoutParams);
867
+ forward.setContentDescription("Forward Button");
868
+ forward.setId(Integer.valueOf(3));
869
+ int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
870
+ Drawable fwdIcon = activityRes.getDrawable(fwdResId);
871
+ if (navigationButtonColor != "") forward.setColorFilter(android.graphics.Color.parseColor(navigationButtonColor));
872
+ forward.setBackground(null);
873
+ forward.setImageDrawable(fwdIcon);
874
+ forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
875
+ forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
876
+ forward.getAdjustViewBounds();
877
+
878
+ forward.setOnClickListener(new View.OnClickListener() {
879
+ public void onClick(View v) {
880
+ goForward();
881
+ }
882
+ });
883
+
884
+ // Edit Text Box
885
+ edittext = new EditText(cordova.getActivity());
886
+ RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
887
+ textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
888
+ textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
889
+ edittext.setLayoutParams(textLayoutParams);
890
+ edittext.setId(Integer.valueOf(4));
891
+ edittext.setSingleLine(true);
892
+ edittext.setText(url);
893
+ edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
894
+ edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
895
+ edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
896
+ edittext.setOnKeyListener(new View.OnKeyListener() {
897
+ public boolean onKey(View v, int keyCode, KeyEvent event) {
898
+ // If the event is a key-down event on the "enter" button
899
+ if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
900
+ navigate(edittext.getText().toString());
901
+ return true;
902
+ }
903
+ return false;
904
+ }
905
+ });
906
+
907
+
908
+ // Header Close/Done button
909
+ int closeButtonId = leftToRight ? 1 : 5;
910
+ View close = createCloseButton(closeButtonId);
911
+ toolbar.addView(close);
912
+
913
+ // Footer
914
+ RelativeLayout footer = new RelativeLayout(cordova.getActivity());
915
+ int _footerColor;
916
+ if(footerColor != "") {
917
+ _footerColor = Color.parseColor(footerColor);
918
+ } else {
919
+ _footerColor = android.graphics.Color.LTGRAY;
920
+ }
921
+ footer.setBackgroundColor(_footerColor);
922
+ RelativeLayout.LayoutParams footerLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(TOOLBAR_HEIGHT));
923
+ footerLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
924
+ footer.setLayoutParams(footerLayout);
925
+ if (closeButtonCaption != "") footer.setPadding(this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8), this.dpToPixels(8));
926
+ footer.setHorizontalGravity(Gravity.LEFT);
927
+ footer.setVerticalGravity(Gravity.BOTTOM);
928
+
929
+ View footerClose = createCloseButton(7);
930
+ footer.addView(footerClose);
931
+
932
+ // WebView
933
+ inAppWebView = new WebView(cordova.getActivity());
934
+ inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
935
+ inAppWebView.setId(Integer.valueOf(6));
936
+ // File Chooser Implemented ChromeClient
937
+ inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView) {
938
+ public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
939
+ {
940
+ LOG.d(LOG_TAG, "File Chooser 5.0+");
941
+ // If callback exists, finish it.
942
+ if(mUploadCallback != null) {
943
+ mUploadCallback.onReceiveValue(null);
944
+ }
945
+ mUploadCallback = filePathCallback;
946
+
947
+ // Create File Chooser Intent
948
+ Intent content = new Intent(Intent.ACTION_GET_CONTENT);
949
+ content.addCategory(Intent.CATEGORY_OPENABLE);
950
+ content.setType("*/*");
951
+
952
+ // Run cordova startActivityForResult
953
+ cordova.startActivityForResult(InAppBrowser.this, Intent.createChooser(content, "Select File"), FILECHOOSER_REQUESTCODE);
954
+ return true;
955
+ }
956
+ });
957
+ currentClient = new InAppBrowserClient(thatWebView, edittext, beforeload);
958
+ inAppWebView.setWebViewClient(currentClient);
959
+ WebSettings settings = inAppWebView.getSettings();
960
+ settings.setJavaScriptEnabled(true);
961
+ settings.setJavaScriptCanOpenWindowsAutomatically(true);
962
+ settings.setBuiltInZoomControls(showZoomControls);
963
+ settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
964
+
965
+ // download event
966
+
967
+ inAppWebView.setDownloadListener(
968
+ new DownloadListener(){
969
+ public void onDownloadStart(
970
+ String url, String userAgent, String contentDisposition, String mimetype, long contentLength
971
+ ){
972
+ try{
973
+ JSONObject succObj = new JSONObject();
974
+ succObj.put("type", DOWNLOAD_EVENT);
975
+ succObj.put("url",url);
976
+ succObj.put("userAgent",userAgent);
977
+ succObj.put("contentDisposition",contentDisposition);
978
+ succObj.put("mimetype",mimetype);
979
+ succObj.put("contentLength",contentLength);
980
+ sendUpdate(succObj, true);
981
+ }
982
+ catch(Exception e){
983
+ LOG.e(LOG_TAG,e.getMessage());
984
+ }
985
+ }
986
+ }
987
+ );
988
+
989
+ // Add postMessage interface
990
+ class JsObject {
991
+ @JavascriptInterface
992
+ public void postMessage(String data) {
993
+ try {
994
+ JSONObject obj = new JSONObject();
995
+ obj.put("type", MESSAGE_EVENT);
996
+ obj.put("data", new JSONObject(data));
997
+ sendUpdate(obj, true);
998
+ } catch (JSONException ex) {
999
+ LOG.e(LOG_TAG, "data object passed to postMessage has caused a JSON error.");
1000
+ }
1001
+ }
1002
+ }
1003
+
1004
+ settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
1005
+ inAppWebView.addJavascriptInterface(new JsObject(), "cordova_iab");
1006
+
1007
+ String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
1008
+ String appendUserAgent = preferences.getString("AppendUserAgent", null);
1009
+
1010
+ if (overrideUserAgent != null) {
1011
+ settings.setUserAgentString(overrideUserAgent);
1012
+ }
1013
+ if (appendUserAgent != null) {
1014
+ settings.setUserAgentString(settings.getUserAgentString() + " " + appendUserAgent);
1015
+ }
1016
+
1017
+ //Toggle whether this is enabled or not!
1018
+ Bundle appSettings = cordova.getActivity().getIntent().getExtras();
1019
+ boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
1020
+ if (enableDatabase) {
1021
+ String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
1022
+ settings.setDatabasePath(databasePath);
1023
+ settings.setDatabaseEnabled(true);
1024
+ }
1025
+ settings.setDomStorageEnabled(true);
1026
+
1027
+ if (clearAllCache) {
1028
+ CookieManager.getInstance().removeAllCookie();
1029
+ } else if (clearSessionCache) {
1030
+ CookieManager.getInstance().removeSessionCookie();
1031
+ }
1032
+
1033
+ // Enable Thirdparty Cookies
1034
+ CookieManager.getInstance().setAcceptThirdPartyCookies(inAppWebView,true);
1035
+
1036
+ inAppWebView.loadUrl(url);
1037
+ inAppWebView.setId(Integer.valueOf(6));
1038
+ inAppWebView.getSettings().setLoadWithOverviewMode(true);
1039
+ inAppWebView.getSettings().setUseWideViewPort(useWideViewPort);
1040
+ // Multiple Windows set to true to mitigate Chromium security bug.
1041
+ // See: https://bugs.chromium.org/p/chromium/issues/detail?id=1083819
1042
+ inAppWebView.getSettings().setSupportMultipleWindows(true);
1043
+ inAppWebView.requestFocus();
1044
+ inAppWebView.requestFocusFromTouch();
1045
+
1046
+ // Add the back and forward buttons to our action button container layout
1047
+ actionButtonContainer.addView(back);
1048
+ actionButtonContainer.addView(forward);
1049
+
1050
+ // Add the views to our toolbar if they haven't been disabled
1051
+ if (!hideNavigationButtons) toolbar.addView(actionButtonContainer);
1052
+ if (!hideUrlBar) toolbar.addView(edittext);
1053
+
1054
+ // Don't add the toolbar if its been disabled
1055
+ if (getShowLocationBar()) {
1056
+ // Add our toolbar to our main view/layout
1057
+ main.addView(toolbar);
1058
+ }
1059
+
1060
+ // Add our webview to our main view/layout
1061
+ RelativeLayout webViewLayout = new RelativeLayout(cordova.getActivity());
1062
+ webViewLayout.addView(inAppWebView);
1063
+ main.addView(webViewLayout);
1064
+
1065
+ // Don't add the footer unless it's been enabled
1066
+ if (showFooter) {
1067
+ webViewLayout.addView(footer);
1068
+ }
1069
+
1070
+ WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
1071
+ lp.copyFrom(dialog.getWindow().getAttributes());
1072
+ lp.width = WindowManager.LayoutParams.MATCH_PARENT;
1073
+ lp.height = WindowManager.LayoutParams.MATCH_PARENT;
1074
+
1075
+ if (dialog != null) {
1076
+ dialog.setContentView(main);
1077
+ dialog.show();
1078
+ dialog.getWindow().setAttributes(lp);
1079
+ }
1080
+ // the goal of openhidden is to load the url and not display it
1081
+ // Show() needs to be called to cause the URL to be loaded
1082
+ if (openWindowHidden && dialog != null) {
1083
+ dialog.hide();
1084
+ }
1085
+ }
1086
+ };
1087
+ this.cordova.getActivity().runOnUiThread(runnable);
1088
+ return "";
1089
+ }
1090
+
1091
+ /**
1092
+ * Create a new plugin success result and send it back to JavaScript
1093
+ *
1094
+ * @param obj a JSONObject contain event payload information
1095
+ */
1096
+ private void sendUpdate(JSONObject obj, boolean keepCallback) {
1097
+ sendUpdate(obj, keepCallback, PluginResult.Status.OK);
1098
+ }
1099
+
1100
+ /**
1101
+ * Create a new plugin result and send it back to JavaScript
1102
+ *
1103
+ * @param obj a JSONObject contain event payload information
1104
+ * @param status the status code to return to the JavaScript environment
1105
+ */
1106
+ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
1107
+ if (callbackContext != null) {
1108
+ PluginResult result = new PluginResult(status, obj);
1109
+ result.setKeepCallback(keepCallback);
1110
+ callbackContext.sendPluginResult(result);
1111
+ if (!keepCallback) {
1112
+ callbackContext = null;
1113
+ }
1114
+ }
1115
+ }
1116
+
1117
+ /**
1118
+ * Receive File Data from File Chooser
1119
+ *
1120
+ * @param requestCode the requested code from chromeclient
1121
+ * @param resultCode the result code returned from android system
1122
+ * @param intent the data from android file chooser
1123
+ */
1124
+ public void onActivityResult(int requestCode, int resultCode, Intent intent) {
1125
+ LOG.d(LOG_TAG, "onActivityResult");
1126
+ // If RequestCode or Callback is Invalid
1127
+ if(requestCode != FILECHOOSER_REQUESTCODE || mUploadCallback == null) {
1128
+ super.onActivityResult(requestCode, resultCode, intent);
1129
+ return;
1130
+ }
1131
+ mUploadCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
1132
+ mUploadCallback = null;
1133
+ }
1134
+
1135
+ /**
1136
+ * The webview client receives notifications about appView
1137
+ */
1138
+ public class InAppBrowserClient extends WebViewClient {
1139
+ EditText edittext;
1140
+ CordovaWebView webView;
1141
+ String beforeload;
1142
+ boolean waitForBeforeload;
1143
+
1144
+ /**
1145
+ * Constructor.
1146
+ *
1147
+ * @param webView
1148
+ * @param mEditText
1149
+ */
1150
+ public InAppBrowserClient(CordovaWebView webView, EditText mEditText, String beforeload) {
1151
+ this.webView = webView;
1152
+ this.edittext = mEditText;
1153
+ this.beforeload = beforeload;
1154
+ this.waitForBeforeload = beforeload != null;
1155
+ }
1156
+
1157
+ /**
1158
+ * Override the URL that should be loaded
1159
+ *
1160
+ * Legacy (deprecated in API 24)
1161
+ * For Android 6 and below.
1162
+ *
1163
+ * @param webView
1164
+ * @param url
1165
+ */
1166
+ @SuppressWarnings("deprecation")
1167
+ @Override
1168
+ public boolean shouldOverrideUrlLoading(WebView webView, String url) {
1169
+ return shouldOverrideUrlLoading(url, null);
1170
+ }
1171
+
1172
+ /**
1173
+ * Override the URL that should be loaded
1174
+ *
1175
+ * New (added in API 24)
1176
+ * For Android 7 and above.
1177
+ *
1178
+ * @param webView
1179
+ * @param request
1180
+ */
1181
+ @TargetApi(Build.VERSION_CODES.N)
1182
+ @Override
1183
+ public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {
1184
+ return shouldOverrideUrlLoading(request.getUrl().toString(), request.getMethod());
1185
+ }
1186
+
1187
+ /**
1188
+ * Override the URL that should be loaded
1189
+ *
1190
+ * This handles a small subset of all the URIs that would be encountered.
1191
+ *
1192
+ * @param url
1193
+ * @param method
1194
+ */
1195
+ public boolean shouldOverrideUrlLoading(String url, String method) {
1196
+ boolean override = false;
1197
+ boolean useBeforeload = false;
1198
+ String errorMessage = null;
1199
+
1200
+ if (beforeload.equals("yes") && method == null) {
1201
+ useBeforeload = true;
1202
+ } else if(beforeload.equals("yes")
1203
+ //TODO handle POST requests then this condition can be removed:
1204
+ && !method.equals("POST"))
1205
+ {
1206
+ useBeforeload = true;
1207
+ } else if(beforeload.equals("get") && (method == null || method.equals("GET"))) {
1208
+ useBeforeload = true;
1209
+ } else if(beforeload.equals("post") && (method == null || method.equals("POST"))) {
1210
+ //TODO handle POST requests
1211
+ errorMessage = "beforeload doesn't yet support POST requests";
1212
+ }
1213
+
1214
+ // On first URL change, initiate JS callback. Only after the beforeload event, continue.
1215
+ if (useBeforeload && this.waitForBeforeload) {
1216
+ if(sendBeforeLoad(url, method)) {
1217
+ return true;
1218
+ }
1219
+ }
1220
+
1221
+ if(errorMessage != null) {
1222
+ try {
1223
+ LOG.e(LOG_TAG, errorMessage);
1224
+ JSONObject obj = new JSONObject();
1225
+ obj.put("type", LOAD_ERROR_EVENT);
1226
+ obj.put("url", url);
1227
+ obj.put("code", -1);
1228
+ obj.put("message", errorMessage);
1229
+ sendUpdate(obj, true, PluginResult.Status.ERROR);
1230
+ } catch(Exception e) {
1231
+ LOG.e(LOG_TAG, "Error sending loaderror for " + url + ": " + e.toString());
1232
+ }
1233
+ }
1234
+
1235
+ if (url.startsWith(WebView.SCHEME_TEL)) {
1236
+ try {
1237
+ Intent intent = new Intent(Intent.ACTION_DIAL);
1238
+ intent.setData(Uri.parse(url));
1239
+ cordova.getActivity().startActivity(intent);
1240
+ override = true;
1241
+ } catch (android.content.ActivityNotFoundException e) {
1242
+ LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
1243
+ }
1244
+ } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
1245
+ try {
1246
+ Intent intent = new Intent(Intent.ACTION_VIEW);
1247
+ intent.setData(Uri.parse(url));
1248
+ cordova.getActivity().startActivity(intent);
1249
+ override = true;
1250
+ } catch (android.content.ActivityNotFoundException e) {
1251
+ LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
1252
+ }
1253
+ }
1254
+ // If sms:5551212?body=This is the message
1255
+ else if (url.startsWith("sms:")) {
1256
+ try {
1257
+ Intent intent = new Intent(Intent.ACTION_VIEW);
1258
+
1259
+ // Get address
1260
+ String address = null;
1261
+ int parmIndex = url.indexOf('?');
1262
+ if (parmIndex == -1) {
1263
+ address = url.substring(4);
1264
+ } else {
1265
+ address = url.substring(4, parmIndex);
1266
+
1267
+ // If body, then set sms body
1268
+ Uri uri = Uri.parse(url);
1269
+ String query = uri.getQuery();
1270
+ if (query != null) {
1271
+ if (query.startsWith("body=")) {
1272
+ intent.putExtra("sms_body", query.substring(5));
1273
+ }
1274
+ }
1275
+ }
1276
+ intent.setData(Uri.parse("sms:" + address));
1277
+ intent.putExtra("address", address);
1278
+ intent.setType("vnd.android-dir/mms-sms");
1279
+ cordova.getActivity().startActivity(intent);
1280
+ override = true;
1281
+ } catch (android.content.ActivityNotFoundException e) {
1282
+ LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
1283
+ }
1284
+ }
1285
+ // Test for whitelisted custom scheme names like mycoolapp:// or twitteroauthresponse:// (Twitter Oauth Response)
1286
+ else if (!url.startsWith("http:") && !url.startsWith("https:") && url.matches("^[A-Za-z0-9+.-]*://.*?$")) {
1287
+ if (allowedSchemes == null) {
1288
+ String allowed = preferences.getString("AllowedSchemes", null);
1289
+ if(allowed != null) {
1290
+ allowedSchemes = allowed.split(",");
1291
+ }
1292
+ }
1293
+ if (allowedSchemes != null) {
1294
+ for (String scheme : allowedSchemes) {
1295
+ if (url.startsWith(scheme)) {
1296
+ try {
1297
+ JSONObject obj = new JSONObject();
1298
+ obj.put("type", "customscheme");
1299
+ obj.put("url", url);
1300
+ sendUpdate(obj, true);
1301
+ override = true;
1302
+ } catch (JSONException ex) {
1303
+ LOG.e(LOG_TAG, "Custom Scheme URI passed in has caused a JSON error.");
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+
1310
+ if (useBeforeload) {
1311
+ this.waitForBeforeload = true;
1312
+ }
1313
+ return override;
1314
+ }
1315
+
1316
+ private boolean sendBeforeLoad(String url, String method) {
1317
+ try {
1318
+ JSONObject obj = new JSONObject();
1319
+ obj.put("type", BEFORELOAD);
1320
+ obj.put("url", url);
1321
+ if(method != null) {
1322
+ obj.put("method", method);
1323
+ }
1324
+ sendUpdate(obj, true);
1325
+ return true;
1326
+ } catch (JSONException ex) {
1327
+ LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
1328
+ }
1329
+ return false;
1330
+ }
1331
+
1332
+ /**
1333
+ * New (added in API 21)
1334
+ * For Android 5.0 and above.
1335
+ *
1336
+ * @param view
1337
+ * @param request
1338
+ */
1339
+ @Override
1340
+ public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
1341
+ return shouldInterceptRequest(request.getUrl().toString(), super.shouldInterceptRequest(view, request), request.getMethod());
1342
+ }
1343
+
1344
+ public WebResourceResponse shouldInterceptRequest(String url, WebResourceResponse response, String method) {
1345
+ return response;
1346
+ }
1347
+
1348
+ /*
1349
+ * onPageStarted fires the LOAD_START_EVENT
1350
+ *
1351
+ * @param view
1352
+ * @param url
1353
+ * @param favicon
1354
+ */
1355
+ @Override
1356
+ public void onPageStarted(WebView view, String url, Bitmap favicon) {
1357
+ super.onPageStarted(view, url, favicon);
1358
+ String newloc = "";
1359
+ if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
1360
+ newloc = url;
1361
+ }
1362
+ else
1363
+ {
1364
+ // Assume that everything is HTTP at this point, because if we don't specify,
1365
+ // it really should be. Complain loudly about this!!!
1366
+ LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
1367
+ newloc = "http://" + url;
1368
+ }
1369
+
1370
+ // Update the UI if we haven't already
1371
+ if (!newloc.equals(edittext.getText().toString())) {
1372
+ edittext.setText(newloc);
1373
+ }
1374
+
1375
+ try {
1376
+ JSONObject obj = new JSONObject();
1377
+ obj.put("type", LOAD_START_EVENT);
1378
+ obj.put("url", newloc);
1379
+ sendUpdate(obj, true);
1380
+ } catch (JSONException ex) {
1381
+ LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
1382
+ }
1383
+ }
1384
+
1385
+ public void onPageFinished(WebView view, String url) {
1386
+ super.onPageFinished(view, url);
1387
+
1388
+ // Set the namespace for postMessage()
1389
+ injectDeferredObject("window.webkit={messageHandlers:{cordova_iab:cordova_iab}}", null);
1390
+
1391
+ // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
1392
+ CookieManager.getInstance().flush();
1393
+
1394
+ // https://issues.apache.org/jira/browse/CB-11248
1395
+ view.clearFocus();
1396
+ view.requestFocus();
1397
+
1398
+ try {
1399
+ JSONObject obj = new JSONObject();
1400
+ obj.put("type", LOAD_STOP_EVENT);
1401
+ obj.put("url", url);
1402
+
1403
+ sendUpdate(obj, true);
1404
+ } catch (JSONException ex) {
1405
+ LOG.d(LOG_TAG, "Should never happen");
1406
+ }
1407
+ }
1408
+
1409
+ public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
1410
+ super.onReceivedError(view, errorCode, description, failingUrl);
1411
+
1412
+ try {
1413
+ JSONObject obj = new JSONObject();
1414
+ obj.put("type", LOAD_ERROR_EVENT);
1415
+ obj.put("url", failingUrl);
1416
+ obj.put("code", errorCode);
1417
+ obj.put("message", description);
1418
+
1419
+ sendUpdate(obj, true, PluginResult.Status.ERROR);
1420
+ } catch (JSONException ex) {
1421
+ LOG.d(LOG_TAG, "Should never happen");
1422
+ }
1423
+ }
1424
+
1425
+ @Override
1426
+ public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1427
+ super.onReceivedSslError(view, handler, error);
1428
+ try {
1429
+ JSONObject obj = new JSONObject();
1430
+ obj.put("type", LOAD_ERROR_EVENT);
1431
+ obj.put("url", error.getUrl());
1432
+ obj.put("code", 0);
1433
+ obj.put("sslerror", error.getPrimaryError());
1434
+ String message;
1435
+ switch (error.getPrimaryError()) {
1436
+ case SslError.SSL_DATE_INVALID:
1437
+ message = "The date of the certificate is invalid";
1438
+ break;
1439
+ case SslError.SSL_EXPIRED:
1440
+ message = "The certificate has expired";
1441
+ break;
1442
+ case SslError.SSL_IDMISMATCH:
1443
+ message = "Hostname mismatch";
1444
+ break;
1445
+ default:
1446
+ case SslError.SSL_INVALID:
1447
+ message = "A generic error occurred";
1448
+ break;
1449
+ case SslError.SSL_NOTYETVALID:
1450
+ message = "The certificate is not yet valid";
1451
+ break;
1452
+ case SslError.SSL_UNTRUSTED:
1453
+ message = "The certificate authority is not trusted";
1454
+ break;
1455
+ }
1456
+ obj.put("message", message);
1457
+
1458
+ sendUpdate(obj, true, PluginResult.Status.ERROR);
1459
+ } catch (JSONException ex) {
1460
+ LOG.d(LOG_TAG, "Should never happen");
1461
+ }
1462
+ handler.cancel();
1463
+ }
1464
+
1465
+ /**
1466
+ * On received http auth request.
1467
+ */
1468
+ @Override
1469
+ public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1470
+
1471
+ // Check if there is some plugin which can resolve this auth challenge
1472
+ PluginManager pluginManager = null;
1473
+ try {
1474
+ Method gpm = webView.getClass().getMethod("getPluginManager");
1475
+ pluginManager = (PluginManager)gpm.invoke(webView);
1476
+ } catch (NoSuchMethodException e) {
1477
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
1478
+ } catch (IllegalAccessException e) {
1479
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
1480
+ } catch (InvocationTargetException e) {
1481
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
1482
+ }
1483
+
1484
+ if (pluginManager == null) {
1485
+ try {
1486
+ Field pmf = webView.getClass().getField("pluginManager");
1487
+ pluginManager = (PluginManager)pmf.get(webView);
1488
+ } catch (NoSuchFieldException e) {
1489
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
1490
+ } catch (IllegalAccessException e) {
1491
+ LOG.d(LOG_TAG, e.getLocalizedMessage());
1492
+ }
1493
+ }
1494
+
1495
+ if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
1496
+ return;
1497
+ }
1498
+
1499
+ // By default handle 401 like we'd normally do!
1500
+ super.onReceivedHttpAuthRequest(view, handler, host, realm);
1501
+ }
1502
+ }
1503
+ }