2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser.
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.
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.
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/>.
20 package com.stoutner.privacybrowser;
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;
58 import java.net.URLEncoder;
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;
66 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
67 private Menu mainMenu;
68 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
69 private String formattedUrlString;
70 // homepage is used in onCreate() and onOptionsItemSelected().
71 private String homepage = "https://www.duckduckgo.com/";
72 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
73 private boolean javaScriptEnabled;
74 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
75 private boolean domStorageEnabled;
77 /* saveFormDataEnabled does nothing until database storage is implemented.
78 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
79 private boolean saveFormDataEnabled;
82 // cookieManager is used in onCreate() and onOptionsItemSelected().
83 private CookieManager cookieManager;
84 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
85 private boolean cookiesEnabled;
87 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
88 private EditText urlTextBox;
91 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
92 @SuppressLint("SetJavaScriptEnabled")
93 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 setContentView(R.layout.activity_webview);
97 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
98 final Activity mainWebViewActivity = this;
99 final ActionBar actionBar = getSupportActionBar();
101 mainWebView = (WebView) findViewById(R.id.mainWebView);
103 if (actionBar != null) {
104 // Remove the title from the action bar.
105 actionBar.setDisplayShowTitleEnabled(false);
107 // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
108 actionBar.setCustomView(R.layout.app_bar);
109 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
111 // Set the "go" button on the keyboard to load the URL in urlTextBox.
112 urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
113 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
114 public boolean onKey(View v, int keyCode, KeyEvent event) {
115 // If the event is a key-down event on the "enter" button, load the URL.
116 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
117 // Load the URL into the mainWebView and consume the event.
119 loadUrlFromTextBox();
120 } catch (UnsupportedEncodingException e) {
123 // If the enter key was pressed, consume the event.
126 // If any other key was pressed, do not consume the event.
133 mainWebView.setWebViewClient(new WebViewClient() {
134 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
136 public boolean shouldOverrideUrlLoading(WebView view, String url) {
137 mainWebView.loadUrl(url);
141 /* These errors do not provide any useful information and clutter the screen.
142 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
143 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
147 // Update the URL in urlTextBox when the page starts to load.
149 public void onPageStarted(WebView view, String url, Bitmap favicon) {
150 urlTextBox.setText(url);
153 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
155 public void onPageFinished(WebView view, String url) {
156 formattedUrlString = url;
157 urlTextBox.setText(formattedUrlString);
161 mainWebView.setWebChromeClient(new WebChromeClient() {
162 // Update the progress bar when a page is loading.
164 public void onProgressChanged(WebView view, int progress) {
165 // Make sure that actionBar is not null.
166 if (actionBar != null) {
167 ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
168 progressBar.setProgress(progress);
169 if (progress < 100) {
170 progressBar.setVisibility(View.VISIBLE);
172 progressBar.setVisibility(View.GONE);
177 // Set the favorite icon when it changes.
179 public void onReceivedIcon(WebView view, Bitmap icon) {
180 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
183 // Place the favorite icon in the actionBar if it is not null.
184 if (actionBar != null) {
185 ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
186 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
190 // Enter full screen video
192 public void onShowCustomView(View view, CustomViewCallback callback) {
193 if (actionBar != null) {
197 fullScreenVideoFrameLayout.addView(view);
198 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
200 mainWebView.setVisibility(View.GONE);
202 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
203 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
204 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
207 // Set the one flag supported by API >= 14.
208 if (Build.VERSION.SDK_INT >= 14) {
209 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
212 // Set the two flags that are supported by API >= 16.
213 if (Build.VERSION.SDK_INT >= 16) {
214 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
217 // Set all three flags that are supported by API >= 19.
218 if (Build.VERSION.SDK_INT >= 19) {
219 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
223 // Exit full screen video
224 public void onHideCustomView() {
225 if (actionBar != null) {
229 mainWebView.setVisibility(View.VISIBLE);
231 fullScreenVideoFrameLayout.removeAllViews();
232 fullScreenVideoFrameLayout.setVisibility(View.GONE);
236 // Allow the downloading of files.
237 mainWebView.setDownloadListener(new DownloadListener() {
238 // Launch the Android download manager when a link leads to a download.
240 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
241 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
242 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
244 // Add the URL as the description for the download.
245 requestUri.setDescription(url);
247 // Show the download notification after the download is completed if the API is 11 or greater.
248 if (Build.VERSION.SDK_INT >= 11) {
249 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
252 downloadManager.enqueue(requestUri);
253 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
257 // Allow pinch to zoom.
258 mainWebView.getSettings().setBuiltInZoomControls(true);
260 // Hide zoom controls if the API is 11 or greater.
261 if (Build.VERSION.SDK_INT >= 11) {
262 mainWebView.getSettings().setDisplayZoomControls(false);
265 // Set JavaScript initial status.
266 javaScriptEnabled = false;
267 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
269 // Set DOM Storage initial status.
270 domStorageEnabled = false;
271 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
273 /* Save Form Data does nothing until database storage is implemented.
274 // Set Save Form Data initial status.
275 saveFormDataEnabled = true;
276 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
279 // Set Cookies initial status.
280 cookiesEnabled = false;
281 cookieManager = CookieManager.getInstance();
282 cookieManager.setAcceptCookie(cookiesEnabled);
284 // Get the intent information that started the app.
285 final Intent intent = getIntent();
287 if (intent.getData() != null) {
288 // Get the intent data and convert it to a string.
289 final Uri intentUriData = intent.getData();
290 formattedUrlString = intentUriData.toString();
293 // If formattedUrlString is null assign the homepage to it.
294 if (formattedUrlString == null) {
295 formattedUrlString = homepage;
298 // Load the initial website.
299 mainWebView.loadUrl(formattedUrlString);
303 protected void onNewIntent(Intent intent) {
304 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
307 if (intent.getData() != null) {
308 // Get the intent data and convert it to a string.
309 final Uri intentUriData = intent.getData();
310 formattedUrlString = intentUriData.toString();
314 mainWebView.loadUrl(formattedUrlString);
318 public boolean onCreateOptionsMenu(Menu menu) {
319 // Inflate the menu; this adds items to the action bar if it is present.
320 getMenuInflater().inflate(R.menu.menu_webview, menu);
322 // Set mainMenu so it can be used by onOptionsItemSelected.
325 // Get MenuItems for checkable menu items.
326 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
327 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
328 /* toggleSaveFormData does nothing until database storage is implemented.
329 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
331 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
333 // Set the initial icon for toggleJavaScript
334 if (javaScriptEnabled) {
335 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
337 if (domStorageEnabled || cookiesEnabled) {
338 toggleJavaScript.setIcon(R.drawable.warning);
340 toggleJavaScript.setIcon(R.drawable.privacy_mode);
344 // Set the initial status of the menu item checkboxes.
345 toggleDomStorage.setChecked(domStorageEnabled);
346 /* toggleSaveFormData does nothing until database storage is implemented.
347 toggleSaveFormData.setChecked(saveFormDataEnabled);
349 toggleCookies.setChecked(cookiesEnabled);
355 public boolean onPrepareOptionsMenu(Menu menu) {
356 // Enable Clear Cookies if there are any.
357 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
358 clearCookies.setEnabled(cookieManager.hasCookies());
360 // Enable Back if canGoBack().
361 MenuItem back = menu.findItem(R.id.back);
362 back.setEnabled(mainWebView.canGoBack());
364 // Enable forward if canGoForward().
365 MenuItem forward = menu.findItem(R.id.forward);
366 forward.setEnabled(mainWebView.canGoForward());
368 // Run all the other default commands.
369 super.onPrepareOptionsMenu(menu);
371 // return true displays the menu.
376 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
378 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
379 @SuppressLint("SetJavaScriptEnabled")
380 // removeAllCookies is deprecated, but it is required for API < 21.
381 @SuppressWarnings("deprecation")
382 public boolean onOptionsItemSelected(MenuItem menuItem) {
383 int menuItemId = menuItem.getItemId();
385 // Some options need to access the clipboard.
386 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
388 // Some options need to update the drawable for toggleJavaScript.
389 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
391 // Sets the commands that relate to the menu entries.
392 switch (menuItemId) {
393 case R.id.toggleJavaScript:
394 if (javaScriptEnabled) {
395 javaScriptEnabled = false;
396 mainWebView.getSettings().setJavaScriptEnabled(false);
397 mainWebView.reload();
399 // Update the toggleJavaScript icon and display a toast message.
400 if (domStorageEnabled || cookiesEnabled) {
401 menuItem.setIcon(R.drawable.warning);
402 if (domStorageEnabled && cookiesEnabled) {
403 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
405 if (domStorageEnabled) {
406 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
408 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
412 menuItem.setIcon(R.drawable.privacy_mode);
413 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
416 javaScriptEnabled = true;
417 menuItem.setIcon(R.drawable.javascript_enabled);
418 mainWebView.getSettings().setJavaScriptEnabled(true);
419 mainWebView.reload();
420 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
424 case R.id.toggleDomStorage:
425 if (domStorageEnabled) {
426 domStorageEnabled = false;
427 menuItem.setChecked(false);
428 mainWebView.getSettings().setDomStorageEnabled(false);
429 mainWebView.reload();
431 // Update the toggleJavaScript icon and display a toast message if appropriate.
432 if (!javaScriptEnabled && !cookiesEnabled) {
433 toggleJavaScript.setIcon(R.drawable.privacy_mode);
434 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
436 if (cookiesEnabled) {
437 toggleJavaScript.setIcon(R.drawable.warning);
438 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
439 } // Else Do nothing because JavaScript is enabled.
442 domStorageEnabled = true;
443 menuItem.setChecked(true);
444 mainWebView.getSettings().setDomStorageEnabled(true);
445 mainWebView.reload();
447 // Update the toggleJavaScript icon if appropriate.
448 if (!javaScriptEnabled) {
449 toggleJavaScript.setIcon(R.drawable.warning);
450 } // Else Do nothing because JavaScript is enabled.
452 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
456 /* toggleSaveFormData does nothing until database storage is implemented.
457 case R.id.toggleSaveFormData:
458 if (saveFormDataEnabled) {
459 saveFormDataEnabled = false;
460 menuItem.setChecked(false);
461 mainWebView.getSettings().setSaveFormData(false);
462 mainWebView.reload();
464 saveFormDataEnabled = true;
465 menuItem.setChecked(true);
466 mainWebView.getSettings().setSaveFormData(true);
467 mainWebView.reload();
472 case R.id.toggleCookies:
473 if (cookiesEnabled) {
474 cookiesEnabled = false;
475 menuItem.setChecked(false);
476 cookieManager.setAcceptCookie(false);
477 mainWebView.reload();
479 // Update the toggleJavaScript icon and display a toast message if appropriate.
480 if (!javaScriptEnabled && !domStorageEnabled) {
481 toggleJavaScript.setIcon(R.drawable.privacy_mode);
482 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
484 if (domStorageEnabled) {
485 toggleJavaScript.setIcon(R.drawable.warning);
486 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
487 } // Else Do nothing because JavaScript is enabled.
490 cookiesEnabled = true;
491 menuItem.setChecked(true);
492 cookieManager.setAcceptCookie(true);
493 mainWebView.reload();
495 // Update the toggleJavaScript icon if appropriate.
496 if (!javaScriptEnabled) {
497 toggleJavaScript.setIcon(R.drawable.warning);
498 } // Else Do nothing because JavaScript is enabled.
500 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
504 case R.id.clearDomStorage:
505 WebStorage webStorage = WebStorage.getInstance();
506 webStorage.deleteAllData();
507 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
510 case R.id.clearCookies:
511 if (Build.VERSION.SDK_INT < 21) {
512 cookieManager.removeAllCookie();
514 cookieManager.removeAllCookies(null);
516 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
520 mainWebView.loadUrl(homepage);
524 mainWebView.reload();
528 mainWebView.goBack();
532 mainWebView.goForward();
536 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
540 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
541 urlTextBox.setText(clipboardData.coerceToText(this));
543 loadUrlFromTextBox();
544 } catch (UnsupportedEncodingException e) {
550 Intent shareIntent = new Intent();
551 shareIntent.setAction(Intent.ACTION_SEND);
552 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
553 shareIntent.setType("text/plain");
554 startActivity(Intent.createChooser(shareIntent, "Share URL"));
557 case R.id.addToHomescreen:
558 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
559 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
560 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
562 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
566 // Launch the system Download Manager.
567 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
569 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
570 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
572 startActivity(downloadManangerIntent);
576 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
577 AppCompatDialogFragment aboutDialog = new AboutDialog();
578 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
581 case R.id.clearAndExit:
582 // Clear DOM storage.
583 WebStorage domStorage = WebStorage.getInstance();
584 domStorage.deleteAllData();
587 if (Build.VERSION.SDK_INT < 21) {
588 cookieManager.removeAllCookie();
590 cookieManager.removeAllCookies(null);
593 // Destroy the internal state of the webview.
594 mainWebView.destroy();
596 // Close Privacy Browser.
601 return super.onOptionsItemSelected(menuItem);
606 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
607 // Do nothing because the user selected "Cancel".
611 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
612 // Get shortcutNameEditText from the alert dialog.
613 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
615 // Create the bookmark shortcut based on formattedUrlString.
616 Intent bookmarkShortcut = new Intent();
617 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
618 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
620 // Place the bookmark shortcut on the home screen.
621 Intent placeBookmarkShortcut = new Intent();
622 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
623 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
624 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
625 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
626 sendBroadcast(placeBookmarkShortcut);
629 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
631 public void onBackPressed() {
632 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
634 if (mainWebView.canGoBack()) {
635 mainWebView.goBack();
637 super.onBackPressed();
641 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
642 // Get the text from urlTextBox and convert it to a string.
643 String unformattedUrlString = urlTextBox.getText().toString();
644 URL unformattedUrl = null;
645 Uri.Builder formattedUri = new Uri.Builder();
647 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
648 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
649 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
650 if (!unformattedUrlString.startsWith("http")) {
651 unformattedUrlString = "http://" + unformattedUrlString;
654 // 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.
656 unformattedUrl = new URL(unformattedUrlString);
657 } catch (MalformedURLException e) {
661 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
662 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
663 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
664 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
665 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
666 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
668 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
669 formattedUrlString = formattedUri.build().toString();
671 // Sanitize the search input and convert it to a DuckDuckGo search.
672 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
674 // Use the correct search URL based on javaScriptEnabled.
675 if (javaScriptEnabled) {
676 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
678 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
682 mainWebView.loadUrl(formattedUrlString);
684 // Hides the keyboard so we can see the webpage.
685 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
686 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);