]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebView.java
d4b134747642db01fd4958838186fb8ea1aab366
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / MainWebView.java
1 /**
2  * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
22 import android.annotation.SuppressLint;
23 import android.annotation.TargetApi;
24 import android.app.Activity;
25 import android.app.DownloadManager;
26 import android.content.ClipData;
27 import android.content.ClipboardManager;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.graphics.Bitmap;
31 import android.net.Uri;
32 import android.os.Build;
33 import android.os.Bundle;
34 import android.support.v4.app.DialogFragment;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.util.Patterns;
39 import android.view.KeyEvent;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.View;
43 import android.view.inputmethod.InputMethodManager;
44 import android.webkit.CookieManager;
45 import android.webkit.DownloadListener;
46 import android.webkit.WebChromeClient;
47 import android.webkit.WebStorage;
48 import android.webkit.WebView;
49 import android.webkit.WebViewClient;
50 import android.widget.EditText;
51 import android.widget.FrameLayout;
52 import android.widget.ImageView;
53 import android.widget.ProgressBar;
54 import android.widget.Toast;
55 import java.io.UnsupportedEncodingException;
56 import java.net.MalformedURLException;
57 import java.net.URL;
58 import java.net.URLEncoder;
59
60 public class MainWebView extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
61     // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
62     public static Bitmap favoriteIcon;
63     // mainWebView is public static so it can be accessed from AboutDialog.  It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
64     public static WebView mainWebView;
65
66     // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
67     private String formattedUrlString;
68     // homepage is used in onCreate() and onOptionsItemSelected().
69     private String homepage = "https://www.duckduckgo.com/";
70     // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
71     private boolean javaScriptEnabled;
72     // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
73     private boolean domStorageEnabled;
74
75     /* saveFormDataEnabled does nothing until database storage is implemented.
76     // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
77     private boolean saveFormDataEnabled;
78     */
79
80     // cookieManager is used in onCreate() and onOptionsItemSelected().
81     private CookieManager cookieManager;
82     // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
83     private boolean cookiesEnabled;
84
85     // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
86     private EditText urlTextBox;
87
88     @Override
89     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
90     @SuppressLint("SetJavaScriptEnabled")
91     protected void onCreate(Bundle savedInstanceState) {
92         super.onCreate(savedInstanceState);
93         setContentView(R.layout.activity_webview);
94
95         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
96         final Activity mainWebViewActivity = this;
97         final ActionBar actionBar = getSupportActionBar();
98
99         mainWebView = (WebView) findViewById(R.id.mainWebView);
100
101         if (actionBar != null) {
102             // Remove the title from the action bar.
103             actionBar.setDisplayShowTitleEnabled(false);
104
105             // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
106             actionBar.setCustomView(R.layout.app_bar);
107             actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
108
109             // Set the "go" button on the keyboard to load the URL in urlTextBox.
110             urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
111             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
112                 public boolean onKey(View v, int keyCode, KeyEvent event) {
113                     // If the event is a key-down event on the "enter" button, load the URL.
114                     if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
115                         // Load the URL into the mainWebView and consume the event.
116                         try {
117                             loadUrlFromTextBox();
118                         } catch (UnsupportedEncodingException e) {
119                             e.printStackTrace();
120                         }
121                         // If the enter key was pressed, consume the event.
122                         return true;
123                     } else {
124                         // If any other key was pressed, do not consume the event.
125                         return false;
126                     }
127                 }
128             });
129         }
130
131         mainWebView.setWebViewClient(new WebViewClient() {
132             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
133             @Override
134             public boolean shouldOverrideUrlLoading(WebView view, String url) {
135                 mainWebView.loadUrl(url);
136                 return true;
137             }
138
139             /* These errors do not provide any useful information and clutter the screen.
140             public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
141                 Toast.makeText(mainWebViewActivity, "Error loading " + request + "   Error: " + error, Toast.LENGTH_SHORT).show();
142             }
143             */
144
145             // Update the URL in urlTextBox when the page starts to load.
146             @Override
147             public void onPageStarted(WebView view, String url, Bitmap favicon) {
148                 urlTextBox.setText(url);
149             }
150
151             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
152             @Override
153             public void onPageFinished(WebView view, String url) {
154                 formattedUrlString = url;
155                 urlTextBox.setText(formattedUrlString);
156             }
157         });
158
159         mainWebView.setWebChromeClient(new WebChromeClient() {
160             // Update the progress bar when a page is loading.
161             @Override
162             public void onProgressChanged(WebView view, int progress) {
163                 // Make sure that actionBar is not null.
164                 if (actionBar != null) {
165                     ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
166                     progressBar.setProgress(progress);
167                     if (progress < 100) {
168                         progressBar.setVisibility(View.VISIBLE);
169                     } else {
170                         progressBar.setVisibility(View.GONE);
171                     }
172                 }
173             }
174
175             // Set the favorite icon when it changes.
176             @Override
177             public void onReceivedIcon(WebView view, Bitmap icon) {
178                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
179                 favoriteIcon = icon;
180
181                 // Place the favorite icon in the actionBar if it is not null.
182                 if (actionBar != null) {
183                     ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
184                     imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
185                 }
186             }
187
188             // Enter full screen video
189             @Override
190             public void onShowCustomView(View view, CustomViewCallback callback) {
191                 if (actionBar != null) {
192                     actionBar.hide();
193                 }
194
195                 fullScreenVideoFrameLayout.addView(view);
196                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
197
198                 mainWebView.setVisibility(View.GONE);
199
200                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
201                 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
202                 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
203                 */
204
205                 // Set the one flag supported by API >= 14.
206                 if (Build.VERSION.SDK_INT >= 14) {
207                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
208                 }
209
210                 // Set the two flags that are supported by API >= 16.
211                 if (Build.VERSION.SDK_INT >= 16) {
212                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
213                 }
214
215                 // Set all three flags that are supported by API >= 19.
216                 if (Build.VERSION.SDK_INT >= 19) {
217                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
218                 }
219             }
220
221             // Exit full screen video
222             public void onHideCustomView() {
223                 if (actionBar != null) {
224                     actionBar.show();
225                 }
226
227                 mainWebView.setVisibility(View.VISIBLE);
228
229                 fullScreenVideoFrameLayout.removeAllViews();
230                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
231             }
232         });
233
234         // Allow the downloading of files.
235         mainWebView.setDownloadListener(new DownloadListener() {
236             // Launch the Android download manager when a link leads to a download.
237             @Override
238             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
239                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
240                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
241
242                 // Add the URL as the description for the download.
243                 requestUri.setDescription(url);
244
245                 // Show the download notification after the download is completed if the API is 11 or greater.
246                 if (Build.VERSION.SDK_INT >= 11) {
247                     requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
248                 }
249
250                 downloadManager.enqueue(requestUri);
251                 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
252             }
253         });
254
255         // Allow pinch to zoom.
256         mainWebView.getSettings().setBuiltInZoomControls(true);
257
258         // Hide zoom controls if the API is 11 or greater.
259         if (Build.VERSION.SDK_INT >= 11) {
260             mainWebView.getSettings().setDisplayZoomControls(false);
261         }
262
263         // Set JavaScript initial status.
264         javaScriptEnabled = false;
265         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
266
267         // Set DOM Storage initial status.
268         domStorageEnabled = false;
269         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
270
271         /* Save Form Data does nothing until database storage is implemented.
272         // Set Save Form Data initial status.
273         saveFormDataEnabled = true;
274         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
275         */
276
277         // Set Cookies initial status.
278         cookiesEnabled = false;
279         cookieManager = CookieManager.getInstance();
280         cookieManager.setAcceptCookie(cookiesEnabled);
281
282         // Get the intent information that started the app.
283         final Intent intent = getIntent();
284
285         if (intent.getData() != null) {
286             // Get the intent data and convert it to a string.
287             final Uri intentUriData = intent.getData();
288             formattedUrlString = intentUriData.toString();
289         }
290
291         // If formattedUrlString is null assign the homepage to it.
292         if (formattedUrlString == null) {
293             formattedUrlString = homepage;
294         }
295
296         // Load the initial website.
297         mainWebView.loadUrl(formattedUrlString);
298     }
299
300     @Override
301     protected void onNewIntent(Intent intent) {
302         // Sets the new intent as the activity intent, so that any future getIntent() picks up this one.
303         setIntent(intent);
304
305         if (intent.getData() != null) {
306             // Get the intent data and convert it to a string.
307             final Uri intentUriData = intent.getData();
308             formattedUrlString = intentUriData.toString();
309         }
310
311         // Load the website.
312         mainWebView.loadUrl(formattedUrlString);
313     }
314
315     @Override
316     public boolean onCreateOptionsMenu(Menu menu) {
317         // Inflate the menu; this adds items to the action bar if it is present.
318         getMenuInflater().inflate(R.menu.menu_webview, menu);
319
320         // Get MenuItems for checkable menu items.
321         MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
322         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
323         /* toggleSaveFormData does nothing until database storage is implemented.
324         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
325         */
326         MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
327
328         // Set the initial icon for toggleJavaScript
329         if (javaScriptEnabled) {
330             toggleJavaScript.setIcon(R.drawable.javascript_on);
331         } else {
332             toggleJavaScript.setIcon(R.drawable.javascript_off);
333         }
334
335         // Set the initial status of the menu item checkboxes.
336         toggleDomStorage.setChecked(domStorageEnabled);
337         /* toggleSaveFormData does nothing until database storage is implemented.
338         toggleSaveFormData.setChecked(saveFormDataEnabled);
339         */
340         toggleCookies.setChecked(cookiesEnabled);
341
342         return true;
343     }
344
345     @Override
346     public boolean onPrepareOptionsMenu(Menu menu) {
347         // Enable Clear Cookies if there are any.
348         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
349         clearCookies.setEnabled(cookieManager.hasCookies());
350
351         // Enable Back if canGoBack().
352         MenuItem back = menu.findItem(R.id.back);
353         back.setEnabled(mainWebView.canGoBack());
354
355         // Enable forward if canGoForward().
356         MenuItem forward = menu.findItem(R.id.forward);
357         forward.setEnabled(mainWebView.canGoForward());
358
359         // Run all the other default commands.
360         super.onPrepareOptionsMenu(menu);
361
362         // return true displays the menu.
363         return true;
364     }
365
366     @Override
367     // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
368     @TargetApi(11)
369     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
370     @SuppressLint("SetJavaScriptEnabled")
371     // removeAllCookies is deprecated, but it is required for API < 21.
372     @SuppressWarnings("deprecation")
373     public boolean onOptionsItemSelected(MenuItem menuItem) {
374         int menuItemId = menuItem.getItemId();
375         ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
376
377         // Sets the commands that relate to the menu entries.
378         switch (menuItemId) {
379             case R.id.toggleJavaScript:
380                 if (javaScriptEnabled) {
381                     javaScriptEnabled = false;
382                     menuItem.setIcon(R.drawable.javascript_off);
383                     mainWebView.getSettings().setJavaScriptEnabled(false);
384                     mainWebView.reload();
385                     Toast.makeText(getApplicationContext(), "JavaScript Disabled", Toast.LENGTH_SHORT).show();
386                 } else {
387                     javaScriptEnabled = true;
388                     menuItem.setIcon(R.drawable.javascript_on);
389                     mainWebView.getSettings().setJavaScriptEnabled(true);
390                     mainWebView.reload();
391                     Toast.makeText(getApplicationContext(), "JavaScript Enabled", Toast.LENGTH_SHORT).show();
392                 }
393                 return true;
394
395             case R.id.toggleDomStorage:
396                 if (domStorageEnabled) {
397                     domStorageEnabled = false;
398                     menuItem.setChecked(false);
399                     mainWebView.getSettings().setDomStorageEnabled(false);
400                     mainWebView.reload();
401                 } else {
402                     domStorageEnabled = true;
403                     menuItem.setChecked(true);
404                     mainWebView.getSettings().setDomStorageEnabled(true);
405                     mainWebView.reload();
406                 }
407                 return true;
408
409             /* toggleSaveFormData does nothing until database storage is implemented.
410             case R.id.toggleSaveFormData:
411                 if (saveFormDataEnabled) {
412                     saveFormDataEnabled = false;
413                     menuItem.setChecked(false);
414                     mainWebView.getSettings().setSaveFormData(false);
415                     mainWebView.reload();
416                 } else {
417                     saveFormDataEnabled = true;
418                     menuItem.setChecked(true);
419                     mainWebView.getSettings().setSaveFormData(true);
420                     mainWebView.reload();
421                 }
422                 return true;
423             */
424
425             case R.id.toggleCookies:
426                 if (cookiesEnabled) {
427                     cookiesEnabled = false;
428                     menuItem.setChecked(false);
429                     cookieManager.setAcceptCookie(false);
430                     mainWebView.reload();
431                 } else {
432                     cookiesEnabled = true;
433                     menuItem.setChecked(true);
434                     cookieManager.setAcceptCookie(true);
435                     mainWebView.reload();
436                 }
437                 return true;
438
439             case R.id.clearDomStorage:
440                 WebStorage webStorage = WebStorage.getInstance();
441                 webStorage.deleteAllData();
442                 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
443                 return true;
444
445             case R.id.clearCookies:
446                 if (Build.VERSION.SDK_INT < 21) {
447                     cookieManager.removeAllCookie();
448                 } else {
449                     cookieManager.removeAllCookies(null);
450                 }
451                 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
452                 return true;
453
454             case R.id.home:
455                 mainWebView.loadUrl(homepage);
456                 return true;
457
458             case R.id.refresh:
459                 mainWebView.reload();
460                 return true;
461
462             case R.id.back:
463                 mainWebView.goBack();
464                 return true;
465
466             case R.id.forward:
467                 mainWebView.goForward();
468                 return true;
469
470             case R.id.copyURL:
471                 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
472                 return true;
473
474             case R.id.pasteURL:
475                 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
476                 urlTextBox.setText(clipboardData.coerceToText(this));
477                     try {
478                         loadUrlFromTextBox();
479                     } catch (UnsupportedEncodingException e) {
480                         e.printStackTrace();
481                     }
482                 return true;
483
484             case R.id.shareURL:
485                 Intent shareIntent = new Intent();
486                 shareIntent.setAction(Intent.ACTION_SEND);
487                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
488                 shareIntent.setType("text/plain");
489                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
490                 return true;
491
492             case R.id.addToHomescreen:
493                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
494                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
495                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
496
497                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
498                 return true;
499
500             case R.id.downloads:
501                 // Launch the system Download Manager.
502                 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
503
504                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
505                 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
506
507                 startActivity(downloadManangerIntent);
508                 return true;
509
510             case R.id.about:
511                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
512                 AppCompatDialogFragment aboutDialog = new AboutDialog();
513                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
514                 return true;
515
516             case R.id.clearAndExit:
517                 // Clear DOM storage.
518                 WebStorage domStorage = WebStorage.getInstance();
519                 domStorage.deleteAllData();
520
521                 // Clear cookies.
522                 if (Build.VERSION.SDK_INT < 21) {
523                     cookieManager.removeAllCookie();
524                 } else {
525                     cookieManager.removeAllCookies(null);
526                 }
527
528                 // Destroy the internal state of the webview.
529                 mainWebView.destroy();
530
531                 // Close Privacy Browser.
532                 finish();
533                 return true;
534
535             default:
536                 return super.onOptionsItemSelected(menuItem);
537         }
538     }
539
540     @Override
541     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
542         // Do nothing because the user selected "Cancel".
543     }
544
545     @Override
546     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
547         // Get shortcutNameEditText from the alert dialog.
548         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
549
550         // Create the bookmark shortcut based on formattedUrlString.
551         Intent bookmarkShortcut = new Intent();
552         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
553         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
554
555         // Place the bookmark shortcut on the home screen.
556         Intent placeBookmarkShortcut = new Intent();
557         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
558         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
559         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
560         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
561         sendBroadcast(placeBookmarkShortcut);
562     }
563
564     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
565     @Override
566     public void onBackPressed() {
567         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
568
569         if (mainWebView.canGoBack()) {
570             mainWebView.goBack();
571         } else {
572             super.onBackPressed();
573         }
574     }
575
576     public void loadUrlFromTextBox() throws UnsupportedEncodingException {
577         // Get the text from urlTextBox and convert it to a string.
578         String unformattedUrlString = urlTextBox.getText().toString();
579         URL unformattedUrl = null;
580         Uri.Builder formattedUri = new Uri.Builder();
581
582         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
583         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
584             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
585             if (!unformattedUrlString.startsWith("http")) {
586                 unformattedUrlString = "http://" + unformattedUrlString;
587             }
588
589             // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
590             try {
591                 unformattedUrl = new URL(unformattedUrlString);
592             } catch (MalformedURLException e) {
593                 e.printStackTrace();
594             }
595
596             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
597             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
598             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
599             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
600             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
601             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
602
603             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
604             formattedUrlString = formattedUri.build().toString();
605         } else {
606             // Sanitize the search input and convert it to a DuckDuckGo search.
607             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
608
609             // Use the correct search URL based on javaScriptEnabled.
610             if (javaScriptEnabled) {
611                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
612             } else {
613                 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
614             }
615         }
616
617         mainWebView.loadUrl(formattedUrlString);
618
619         // Hides the keyboard so we can see the webpage.
620         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
621         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
622     }
623 }