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.content.SharedPreferences;
31 import android.graphics.Bitmap;
32 import android.net.Uri;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.support.v4.app.DialogFragment;
37 import android.support.v7.app.ActionBar;
38 import android.support.v7.app.AppCompatActivity;
39 import android.support.v7.app.AppCompatDialogFragment;
40 import android.util.Patterns;
41 import android.view.KeyEvent;
42 import android.view.Menu;
43 import android.view.MenuItem;
44 import android.view.View;
45 import android.view.inputmethod.InputMethodManager;
46 import android.webkit.CookieManager;
47 import android.webkit.DownloadListener;
48 import android.webkit.WebChromeClient;
49 import android.webkit.WebStorage;
50 import android.webkit.WebView;
51 import android.webkit.WebViewClient;
52 import android.widget.EditText;
53 import android.widget.FrameLayout;
54 import android.widget.ImageView;
55 import android.widget.ProgressBar;
56 import android.widget.Toast;
57 import java.io.UnsupportedEncodingException;
58 import java.net.MalformedURLException;
60 import java.net.URLEncoder;
62 public class MainWebView extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
63 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
64 public static Bitmap favoriteIcon;
65 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
66 public static WebView mainWebView;
68 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
69 private Menu mainMenu;
70 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
71 private String formattedUrlString;
72 // homepage is used in onCreate() and onOptionsItemSelected().
73 private String homepage;
74 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
75 private boolean javaScriptEnabled;
76 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
77 private boolean domStorageEnabled;
79 /* saveFormDataEnabled does nothing until database storage is implemented.
80 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
81 private boolean saveFormDataEnabled;
84 // cookieManager is used in onCreate() and onOptionsItemSelected().
85 private CookieManager cookieManager;
86 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
87 private boolean cookiesEnabled;
89 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
90 private EditText urlTextBox;
93 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
94 @SuppressLint("SetJavaScriptEnabled")
95 protected void onCreate(Bundle savedInstanceState) {
96 super.onCreate(savedInstanceState);
97 setContentView(R.layout.activity_webview);
99 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
100 final Activity mainWebViewActivity = this;
101 final ActionBar actionBar = getSupportActionBar();
103 mainWebView = (WebView) findViewById(R.id.mainWebView);
105 if (actionBar != null) {
106 // Remove the title from the action bar.
107 actionBar.setDisplayShowTitleEnabled(false);
109 // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
110 actionBar.setCustomView(R.layout.app_bar);
111 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
113 // Set the "go" button on the keyboard to load the URL in urlTextBox.
114 urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
115 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
116 public boolean onKey(View v, int keyCode, KeyEvent event) {
117 // If the event is a key-down event on the "enter" button, load the URL.
118 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
119 // Load the URL into the mainWebView and consume the event.
121 loadUrlFromTextBox();
122 } catch (UnsupportedEncodingException e) {
125 // If the enter key was pressed, consume the event.
128 // If any other key was pressed, do not consume the event.
135 mainWebView.setWebViewClient(new WebViewClient() {
136 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
138 public boolean shouldOverrideUrlLoading(WebView view, String url) {
139 mainWebView.loadUrl(url);
143 /* These errors do not provide any useful information and clutter the screen.
144 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
145 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
149 // Update the URL in urlTextBox when the page starts to load.
151 public void onPageStarted(WebView view, String url, Bitmap favicon) {
152 urlTextBox.setText(url);
155 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
157 public void onPageFinished(WebView view, String url) {
158 formattedUrlString = url;
159 urlTextBox.setText(formattedUrlString);
163 mainWebView.setWebChromeClient(new WebChromeClient() {
164 // Update the progress bar when a page is loading.
166 public void onProgressChanged(WebView view, int progress) {
167 // Make sure that actionBar is not null.
168 if (actionBar != null) {
169 ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
170 progressBar.setProgress(progress);
171 if (progress < 100) {
172 progressBar.setVisibility(View.VISIBLE);
174 progressBar.setVisibility(View.GONE);
179 // Set the favorite icon when it changes.
181 public void onReceivedIcon(WebView view, Bitmap icon) {
182 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
185 // Place the favorite icon in the actionBar if it is not null.
186 if (actionBar != null) {
187 ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
188 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
192 // Enter full screen video
194 public void onShowCustomView(View view, CustomViewCallback callback) {
195 if (actionBar != null) {
199 fullScreenVideoFrameLayout.addView(view);
200 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
202 mainWebView.setVisibility(View.GONE);
204 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
205 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
206 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
209 // Set the one flag supported by API >= 14.
210 if (Build.VERSION.SDK_INT >= 14) {
211 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
214 // Set the two flags that are supported by API >= 16.
215 if (Build.VERSION.SDK_INT >= 16) {
216 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
219 // Set all three flags that are supported by API >= 19.
220 if (Build.VERSION.SDK_INT >= 19) {
221 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
225 // Exit full screen video
226 public void onHideCustomView() {
227 if (actionBar != null) {
231 mainWebView.setVisibility(View.VISIBLE);
233 fullScreenVideoFrameLayout.removeAllViews();
234 fullScreenVideoFrameLayout.setVisibility(View.GONE);
238 // Allow the downloading of files.
239 mainWebView.setDownloadListener(new DownloadListener() {
240 // Launch the Android download manager when a link leads to a download.
242 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
243 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
244 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
246 // Add the URL as the description for the download.
247 requestUri.setDescription(url);
249 // Show the download notification after the download is completed if the API is 11 or greater.
250 if (Build.VERSION.SDK_INT >= 11) {
251 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
254 downloadManager.enqueue(requestUri);
255 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
259 // Allow pinch to zoom.
260 mainWebView.getSettings().setBuiltInZoomControls(true);
262 // Hide zoom controls if the API is 11 or greater.
263 if (Build.VERSION.SDK_INT >= 11) {
264 mainWebView.getSettings().setDisplayZoomControls(false);
267 // Initialize the default preference values the first time the program is run.
268 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
270 // Get the shared preference values.
271 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
273 // Set JavaScript initial status.
274 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
275 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
277 // Set DOM storage initial status.
278 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
279 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
281 /* Save Form Data does nothing until database storage is implemented.
282 // Set Save Form Data initial status.
283 saveFormDataEnabled = true;
284 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
287 // Set cookies initial status.
288 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
289 cookieManager = CookieManager.getInstance();
290 cookieManager.setAcceptCookie(cookiesEnabled);
292 // Set hompage initial status.
293 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
295 // Get the intent information that started the app.
296 final Intent intent = getIntent();
298 if (intent.getData() != null) {
299 // Get the intent data and convert it to a string.
300 final Uri intentUriData = intent.getData();
301 formattedUrlString = intentUriData.toString();
304 // If formattedUrlString is null assign the homepage to it.
305 if (formattedUrlString == null) {
306 formattedUrlString = homepage;
309 // Load the initial website.
310 mainWebView.loadUrl(formattedUrlString);
314 protected void onNewIntent(Intent intent) {
315 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
318 if (intent.getData() != null) {
319 // Get the intent data and convert it to a string.
320 final Uri intentUriData = intent.getData();
321 formattedUrlString = intentUriData.toString();
325 mainWebView.loadUrl(formattedUrlString);
329 public boolean onCreateOptionsMenu(Menu menu) {
330 // Inflate the menu; this adds items to the action bar if it is present.
331 getMenuInflater().inflate(R.menu.menu_webview, menu);
333 // Set mainMenu so it can be used by onOptionsItemSelected.
336 // Get MenuItems for checkable menu items.
337 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
338 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
339 /* toggleSaveFormData does nothing until database storage is implemented.
340 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
342 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
344 // Set the initial icon for toggleJavaScript
345 if (javaScriptEnabled) {
346 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
348 if (domStorageEnabled || cookiesEnabled) {
349 toggleJavaScript.setIcon(R.drawable.warning);
351 toggleJavaScript.setIcon(R.drawable.privacy_mode);
355 // Set the initial status of the menu item checkboxes.
356 toggleDomStorage.setChecked(domStorageEnabled);
357 /* toggleSaveFormData does nothing until database storage is implemented.
358 toggleSaveFormData.setChecked(saveFormDataEnabled);
360 toggleCookies.setChecked(cookiesEnabled);
366 public boolean onPrepareOptionsMenu(Menu menu) {
367 // Enable Clear Cookies if there are any.
368 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
369 clearCookies.setEnabled(cookieManager.hasCookies());
371 // Enable Back if canGoBack().
372 MenuItem back = menu.findItem(R.id.back);
373 back.setEnabled(mainWebView.canGoBack());
375 // Enable forward if canGoForward().
376 MenuItem forward = menu.findItem(R.id.forward);
377 forward.setEnabled(mainWebView.canGoForward());
379 // Run all the other default commands.
380 super.onPrepareOptionsMenu(menu);
382 // return true displays the menu.
387 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
389 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
390 @SuppressLint("SetJavaScriptEnabled")
391 // removeAllCookies is deprecated, but it is required for API < 21.
392 @SuppressWarnings("deprecation")
393 public boolean onOptionsItemSelected(MenuItem menuItem) {
394 int menuItemId = menuItem.getItemId();
396 // Some options need to access the clipboard.
397 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
399 // Some options need to update the drawable for toggleJavaScript.
400 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
402 // Sets the commands that relate to the menu entries.
403 switch (menuItemId) {
404 case R.id.toggleJavaScript:
405 if (javaScriptEnabled) {
406 javaScriptEnabled = false;
407 mainWebView.getSettings().setJavaScriptEnabled(false);
408 mainWebView.reload();
410 // Update the toggleJavaScript icon and display a toast message.
411 if (domStorageEnabled || cookiesEnabled) {
412 menuItem.setIcon(R.drawable.warning);
413 if (domStorageEnabled && cookiesEnabled) {
414 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
416 if (domStorageEnabled) {
417 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
419 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
423 menuItem.setIcon(R.drawable.privacy_mode);
424 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
427 javaScriptEnabled = true;
428 menuItem.setIcon(R.drawable.javascript_enabled);
429 mainWebView.getSettings().setJavaScriptEnabled(true);
430 mainWebView.reload();
431 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
435 case R.id.toggleDomStorage:
436 if (domStorageEnabled) {
437 domStorageEnabled = false;
438 menuItem.setChecked(false);
439 mainWebView.getSettings().setDomStorageEnabled(false);
440 mainWebView.reload();
442 // Update the toggleJavaScript icon and display a toast message if appropriate.
443 if (!javaScriptEnabled && !cookiesEnabled) {
444 toggleJavaScript.setIcon(R.drawable.privacy_mode);
445 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
447 if (cookiesEnabled) {
448 toggleJavaScript.setIcon(R.drawable.warning);
449 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
450 } // Else Do nothing because JavaScript is enabled.
453 domStorageEnabled = true;
454 menuItem.setChecked(true);
455 mainWebView.getSettings().setDomStorageEnabled(true);
456 mainWebView.reload();
458 // Update the toggleJavaScript icon if appropriate.
459 if (!javaScriptEnabled) {
460 toggleJavaScript.setIcon(R.drawable.warning);
461 } // Else Do nothing because JavaScript is enabled.
463 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
467 /* toggleSaveFormData does nothing until database storage is implemented.
468 case R.id.toggleSaveFormData:
469 if (saveFormDataEnabled) {
470 saveFormDataEnabled = false;
471 menuItem.setChecked(false);
472 mainWebView.getSettings().setSaveFormData(false);
473 mainWebView.reload();
475 saveFormDataEnabled = true;
476 menuItem.setChecked(true);
477 mainWebView.getSettings().setSaveFormData(true);
478 mainWebView.reload();
483 case R.id.toggleCookies:
484 if (cookiesEnabled) {
485 cookiesEnabled = false;
486 menuItem.setChecked(false);
487 cookieManager.setAcceptCookie(false);
488 mainWebView.reload();
490 // Update the toggleJavaScript icon and display a toast message if appropriate.
491 if (!javaScriptEnabled && !domStorageEnabled) {
492 toggleJavaScript.setIcon(R.drawable.privacy_mode);
493 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
495 if (domStorageEnabled) {
496 toggleJavaScript.setIcon(R.drawable.warning);
497 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
498 } // Else Do nothing because JavaScript is enabled.
501 cookiesEnabled = true;
502 menuItem.setChecked(true);
503 cookieManager.setAcceptCookie(true);
504 mainWebView.reload();
506 // Update the toggleJavaScript icon if appropriate.
507 if (!javaScriptEnabled) {
508 toggleJavaScript.setIcon(R.drawable.warning);
509 } // Else Do nothing because JavaScript is enabled.
511 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
515 case R.id.clearDomStorage:
516 WebStorage webStorage = WebStorage.getInstance();
517 webStorage.deleteAllData();
518 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
521 case R.id.clearCookies:
522 if (Build.VERSION.SDK_INT < 21) {
523 cookieManager.removeAllCookie();
525 cookieManager.removeAllCookies(null);
527 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
531 mainWebView.loadUrl(homepage);
535 mainWebView.reload();
539 mainWebView.goBack();
543 mainWebView.goForward();
547 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
551 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
552 urlTextBox.setText(clipboardData.coerceToText(this));
554 loadUrlFromTextBox();
555 } catch (UnsupportedEncodingException e) {
561 Intent shareIntent = new Intent();
562 shareIntent.setAction(Intent.ACTION_SEND);
563 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
564 shareIntent.setType("text/plain");
565 startActivity(Intent.createChooser(shareIntent, "Share URL"));
568 case R.id.addToHomescreen:
569 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
570 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
571 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
573 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
577 // Launch the system Download Manager.
578 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
580 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
581 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
583 startActivity(downloadManangerIntent);
587 // Start the Settings activity.
588 Intent intent = new Intent(this, Settings.class);
589 startActivity(intent);
593 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
594 AppCompatDialogFragment aboutDialog = new AboutDialog();
595 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
598 case R.id.clearAndExit:
599 // Clear DOM storage.
600 WebStorage domStorage = WebStorage.getInstance();
601 domStorage.deleteAllData();
604 if (Build.VERSION.SDK_INT < 21) {
605 cookieManager.removeAllCookie();
607 cookieManager.removeAllCookies(null);
610 // Destroy the internal state of the webview.
611 mainWebView.destroy();
613 // Close Privacy Browser.
618 return super.onOptionsItemSelected(menuItem);
623 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
624 // Do nothing because the user selected "Cancel".
628 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
629 // Get shortcutNameEditText from the alert dialog.
630 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
632 // Create the bookmark shortcut based on formattedUrlString.
633 Intent bookmarkShortcut = new Intent();
634 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
635 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
637 // Place the bookmark shortcut on the home screen.
638 Intent placeBookmarkShortcut = new Intent();
639 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
640 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
641 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
642 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
643 sendBroadcast(placeBookmarkShortcut);
646 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
648 public void onBackPressed() {
649 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
651 if (mainWebView.canGoBack()) {
652 mainWebView.goBack();
654 super.onBackPressed();
658 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
659 // Get the text from urlTextBox and convert it to a string.
660 String unformattedUrlString = urlTextBox.getText().toString();
661 URL unformattedUrl = null;
662 Uri.Builder formattedUri = new Uri.Builder();
664 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
665 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
666 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
667 if (!unformattedUrlString.startsWith("http")) {
668 unformattedUrlString = "http://" + unformattedUrlString;
671 // 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.
673 unformattedUrl = new URL(unformattedUrlString);
674 } catch (MalformedURLException e) {
678 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
679 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
680 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
681 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
682 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
683 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
685 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
686 formattedUrlString = formattedUri.build().toString();
688 // Sanitize the search input and convert it to a DuckDuckGo search.
689 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
691 // Use the correct search URL based on javaScriptEnabled.
692 if (javaScriptEnabled) {
693 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
695 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
699 mainWebView.loadUrl(formattedUrlString);
701 // Hides the keyboard so we can see the webpage.
702 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
703 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);