2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/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.app.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslCertificate;
34 import android.net.http.SslError;
35 import android.os.Build;
36 import android.os.Bundle;
37 import android.preference.PreferenceManager;
38 import android.support.annotation.NonNull;
39 import android.support.design.widget.NavigationView;
40 import android.support.design.widget.Snackbar;
41 import android.support.v4.app.ActivityCompat;
42 import android.support.v4.content.ContextCompat;
43 import android.support.v4.view.GravityCompat;
44 import android.support.v4.widget.DrawerLayout;
45 import android.support.v4.widget.SwipeRefreshLayout;
46 import android.support.v7.app.ActionBar;
47 import android.support.v7.app.ActionBarDrawerToggle;
48 import android.support.v7.app.AppCompatActivity;
49 import android.support.v7.widget.Toolbar;
50 import android.util.Patterns;
51 import android.view.KeyEvent;
52 import android.view.Menu;
53 import android.view.MenuItem;
54 import android.view.View;
55 import android.view.inputmethod.InputMethodManager;
56 import android.webkit.CookieManager;
57 import android.webkit.DownloadListener;
58 import android.webkit.SslErrorHandler;
59 import android.webkit.WebChromeClient;
60 import android.webkit.WebStorage;
61 import android.webkit.WebView;
62 import android.webkit.WebViewClient;
63 import android.webkit.WebViewDatabase;
64 import android.widget.EditText;
65 import android.widget.FrameLayout;
66 import android.widget.ImageView;
67 import android.widget.ProgressBar;
69 import java.io.UnsupportedEncodingException;
70 import java.net.MalformedURLException;
72 import java.net.URLEncoder;
73 import java.util.HashMap;
76 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
77 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
78 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
80 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
81 // It is also used in `onCreate()`.
82 public static ActionBar appBar;
84 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
85 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
86 public static Bitmap favoriteIcon;
88 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
89 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
90 public static String formattedUrlString;
92 // `customHeader` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
93 public static Map<String, String> customHeaders = new HashMap<>();
95 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
96 public static SslCertificate sslCertificate;
99 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `loadUrlFromTextBox()`.
100 private WebView mainWebView;
102 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
103 private SwipeRefreshLayout swipeRefreshLayout;
105 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
106 private CookieManager cookieManager;
108 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
109 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
110 private Boolean javaScriptEnabled;
112 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
113 private boolean firstPartyCookiesEnabled;
115 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
116 private boolean thirdPartyCookiesEnabled;
118 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
119 private boolean domStorageEnabled;
121 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
122 private boolean saveFormDataEnabled;
124 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
125 private boolean swipeToRefreshEnabled;
127 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
128 private String homepage;
130 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
131 private String javaScriptDisabledSearchURL;
133 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
134 private String javaScriptEnabledSearchURL;
136 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
137 private Menu mainMenu;
139 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
140 private ActionBarDrawerToggle drawerToggle;
142 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
143 private DrawerLayout drawerLayout;
145 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
146 private EditText urlTextBox;
148 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
151 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
152 private SslErrorHandler sslErrorHandler;
155 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
156 @SuppressLint("SetJavaScriptEnabled")
157 protected void onCreate(Bundle savedInstanceState) {
158 super.onCreate(savedInstanceState);
159 setContentView(R.layout.main_coordinatorlayout);
161 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
162 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
163 setSupportActionBar(supportAppBar);
164 appBar = getSupportActionBar();
166 // This is needed to get rid of the Android Studio warning that appBar might be null.
167 assert appBar != null;
169 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
170 appBar.setCustomView(R.layout.url_bar);
171 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
173 // Set the "go" button on the keyboard to load the URL in urlTextBox.
174 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
175 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
176 public boolean onKey(View v, int keyCode, KeyEvent event) {
177 // If the event is a key-down event on the "enter" button, load the URL.
178 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
179 // Load the URL into the mainWebView and consume the event.
181 loadUrlFromTextBox();
182 } catch (UnsupportedEncodingException e) {
185 // If the enter key was pressed, consume the event.
188 // If any other key was pressed, do not consume the event.
194 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
196 // Implement swipe to refresh
197 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
198 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
199 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
201 public void onRefresh() {
202 mainWebView.reload();
206 mainWebView = (WebView) findViewById(R.id.mainWebView);
208 // Create the navigation drawer.
209 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
210 // The DrawerTitle identifies the drawer in accessibility mode.
211 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
213 // Listen for touches on the navigation menu.
214 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
215 navigationView.setNavigationItemSelectedListener(this);
217 // drawerToggle creates the hamburger icon at the start of the AppBar.
218 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
220 mainWebView.setWebViewClient(new WebViewClient() {
221 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
222 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
223 @SuppressWarnings("deprecation")
225 public boolean shouldOverrideUrlLoading(WebView view, String url) {
226 // Use an external email program if the link begins with "mailto:".
227 if (url.startsWith("mailto:")) {
228 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
229 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
231 // Parse the url and set it as the data for the `Intent`.
232 emailIntent.setData(Uri.parse(url));
234 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
235 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
238 startActivity(emailIntent);
240 } else { // Load the URL in Privacy Browser.
241 mainWebView.loadUrl(url, customHeaders);
246 // Update the URL in urlTextBox when the page starts to load.
248 public void onPageStarted(WebView view, String url, Bitmap favicon) {
249 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
250 formattedUrlString = url;
252 // Display the loading URL is the URL text box.
253 urlTextBox.setText(url);
256 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
258 public void onPageFinished(WebView view, String url) {
259 formattedUrlString = url;
261 // Only update urlTextBox if the user is not typing in it.
262 if (!urlTextBox.hasFocus()) {
263 urlTextBox.setText(formattedUrlString);
266 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
267 sslCertificate = mainWebView.getCertificate();
270 // Handle SSL Certificate errors.
272 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
273 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
274 sslErrorHandler = handler;
276 // Display the SSL error `AlertDialog`.
277 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
278 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
282 mainWebView.setWebChromeClient(new WebChromeClient() {
283 // Update the progress bar when a page is loading.
285 public void onProgressChanged(WebView view, int progress) {
286 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
287 progressBar.setProgress(progress);
288 if (progress < 100) {
289 progressBar.setVisibility(View.VISIBLE);
291 progressBar.setVisibility(View.GONE);
293 //Stop the `SwipeToRefresh` indicator if it is running
294 swipeRefreshLayout.setRefreshing(false);
298 // Set the favorite icon when it changes.
300 public void onReceivedIcon(WebView view, Bitmap icon) {
301 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
304 // Place the favorite icon in the appBar.
305 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
306 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
309 // Enter full screen video
311 public void onShowCustomView(View view, CustomViewCallback callback) {
314 // Show the fullScreenVideoFrameLayout.
315 fullScreenVideoFrameLayout.addView(view);
316 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
318 // Hide the mainWebView.
319 mainWebView.setVisibility(View.GONE);
321 // Hide the ad if this is the free flavor.
322 BannerAd.hideAd(adView);
324 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
325 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
326 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
328 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
331 // Exit full screen video
332 public void onHideCustomView() {
335 // Show the mainWebView.
336 mainWebView.setVisibility(View.VISIBLE);
338 // Show the ad if this is the free flavor.
339 BannerAd.showAd(adView);
341 // Hide the fullScreenVideoFrameLayout.
342 fullScreenVideoFrameLayout.removeAllViews();
343 fullScreenVideoFrameLayout.setVisibility(View.GONE);
347 // Allow the downloading of files.
348 mainWebView.setDownloadListener(new DownloadListener() {
350 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
351 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
352 DialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
353 downloadFileDialogFragment.show(getFragmentManager(), getResources().getString(R.string.download));
357 // Allow pinch to zoom.
358 mainWebView.getSettings().setBuiltInZoomControls(true);
360 // Hide zoom controls.
361 mainWebView.getSettings().setDisplayZoomControls(false);
363 // Initialize cookieManager.
364 cookieManager = CookieManager.getInstance();
366 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
367 customHeaders.put("X-Requested-With", "");
369 // Initialize the default preference values the first time the program is run.
370 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
372 // Apply the settings from the shared preferences.
375 // Get the intent information that started the app.
376 final Intent intent = getIntent();
378 if (intent.getData() != null) {
379 // Get the intent data and convert it to a string.
380 final Uri intentUriData = intent.getData();
381 formattedUrlString = intentUriData.toString();
384 // If formattedUrlString is null assign the homepage to it.
385 if (formattedUrlString == null) {
386 formattedUrlString = homepage;
389 // Load the initial website.
390 mainWebView.loadUrl(formattedUrlString, customHeaders);
392 // If the favorite icon is null, load the default.
393 if (favoriteIcon == null) {
394 // We have to use `ContextCompat` until API >= 21.
395 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
396 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
397 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
400 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
401 adView = findViewById(R.id.adView);
402 BannerAd.requestAd(adView);
407 protected void onNewIntent(Intent intent) {
408 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
411 if (intent.getData() != null) {
412 // Get the intent data and convert it to a string.
413 final Uri intentUriData = intent.getData();
414 formattedUrlString = intentUriData.toString();
417 // Close the navigation drawer if it is open.
418 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
419 drawerLayout.closeDrawer(GravityCompat.START);
423 mainWebView.loadUrl(formattedUrlString, customHeaders);
425 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
426 mainWebView.requestFocus();
430 public boolean onCreateOptionsMenu(Menu menu) {
431 // Inflate the menu; this adds items to the action bar if it is present.
432 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
434 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
437 // Set the initial status of the privacy icons.
438 updatePrivacyIcons();
440 // Get handles for the menu items.
441 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
442 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
443 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
444 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
446 // Only display third-Party Cookies if SDK >= 21
447 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
449 // Get the shared preference values. `this` references the current context.
450 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
452 // Set the status of the additional app bar icons. The default is `false`.
453 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
454 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
455 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
456 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
457 } else { //Do not display the additional icons.
458 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
459 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
460 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
467 public boolean onPrepareOptionsMenu(Menu menu) {
468 // Get handles for the menu items.
469 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
470 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
471 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
472 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
473 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
474 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
475 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
477 // Set the status of the menu item checkboxes.
478 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
479 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
480 toggleDomStorage.setChecked(domStorageEnabled);
481 toggleSaveFormData.setChecked(saveFormDataEnabled);
483 // Enable third-party cookies if first-party cookies are enabled.
484 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
486 // Enable DOM Storage if JavaScript is enabled.
487 toggleDomStorage.setEnabled(javaScriptEnabled);
489 // Enable Clear Cookies if there are any.
490 clearCookies.setEnabled(cookieManager.hasCookies());
492 // Enable Clear Form Data is there is any.
493 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
494 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
496 // Only show `Refresh` if `swipeToRefresh` is disabled.
497 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
499 // Initialize font size variables.
500 int fontSize = mainWebView.getSettings().getTextZoom();
501 String fontSizeTitle;
502 MenuItem selectedFontSizeMenuItem;
504 // Prepare the font size title and current size menu item.
507 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
508 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
512 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
513 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
517 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
518 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
522 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
523 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
527 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
528 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
532 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
533 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
537 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
538 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
542 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
543 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
547 // Set the font size title and select the current size menu item.
548 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
549 fontSizeMenuItem.setTitle(fontSizeTitle);
550 selectedFontSizeMenuItem.setChecked(true);
552 // Run all the other default commands.
553 super.onPrepareOptionsMenu(menu);
555 // `return true` displays the menu.
560 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
561 @SuppressLint("SetJavaScriptEnabled")
562 // removeAllCookies is deprecated, but it is required for API < 21.
563 @SuppressWarnings("deprecation")
564 public boolean onOptionsItemSelected(MenuItem menuItem) {
565 int menuItemId = menuItem.getItemId();
567 // Set the commands that relate to the menu entries.
568 switch (menuItemId) {
569 case R.id.toggleJavaScript:
570 // Switch the status of javaScriptEnabled.
571 javaScriptEnabled = !javaScriptEnabled;
573 // Apply the new JavaScript status.
574 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
576 // Update the privacy icon.
577 updatePrivacyIcons();
579 // Display a `Snackbar`.
580 if (javaScriptEnabled) { // JavaScrip is enabled.
581 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
582 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
583 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
584 } else { // Privacy mode.
585 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
588 // Reload the WebView.
589 mainWebView.reload();
592 case R.id.toggleFirstPartyCookies:
593 // Switch the status of firstPartyCookiesEnabled.
594 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
596 // Update the menu checkbox.
597 menuItem.setChecked(firstPartyCookiesEnabled);
599 // Apply the new cookie status.
600 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
602 // Update the privacy icon.
603 updatePrivacyIcons();
605 // Display a `Snackbar`.
606 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
607 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
608 } else if (javaScriptEnabled){ // JavaScript is still enabled.
609 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
610 } else { // Privacy mode.
611 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
614 // Reload the WebView.
615 mainWebView.reload();
618 case R.id.toggleThirdPartyCookies:
619 if (Build.VERSION.SDK_INT >= 21) {
620 // Switch the status of thirdPartyCookiesEnabled.
621 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
623 // Update the menu checkbox.
624 menuItem.setChecked(thirdPartyCookiesEnabled);
626 // Apply the new cookie status.
627 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
629 // Display a `Snackbar`.
630 if (thirdPartyCookiesEnabled) {
631 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
633 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
636 // Reload the WebView.
637 mainWebView.reload();
638 } // Else do nothing because SDK < 21.
641 case R.id.toggleDomStorage:
642 // Switch the status of domStorageEnabled.
643 domStorageEnabled = !domStorageEnabled;
645 // Update the menu checkbox.
646 menuItem.setChecked(domStorageEnabled);
648 // Apply the new DOM Storage status.
649 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
651 // Display a `Snackbar`.
652 if (domStorageEnabled) {
653 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
655 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
658 // Reload the WebView.
659 mainWebView.reload();
662 case R.id.toggleSaveFormData:
663 // Switch the status of saveFormDataEnabled.
664 saveFormDataEnabled = !saveFormDataEnabled;
666 // Update the menu checkbox.
667 menuItem.setChecked(saveFormDataEnabled);
669 // Apply the new form data status.
670 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
672 // Display a `Snackbar`.
673 if (saveFormDataEnabled) {
674 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
676 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
679 // Reload the WebView.
680 mainWebView.reload();
683 case R.id.clearCookies:
684 if (Build.VERSION.SDK_INT < 21) {
685 cookieManager.removeAllCookie();
687 cookieManager.removeAllCookies(null);
689 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
692 case R.id.clearDomStorage:
693 WebStorage webStorage = WebStorage.getInstance();
694 webStorage.deleteAllData();
695 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
698 case R.id.clearFormData:
699 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
700 mainWebViewDatabase.clearFormData();
701 mainWebView.reload();
704 case R.id.fontSizeFiftyPercent:
705 mainWebView.getSettings().setTextZoom(50);
708 case R.id.fontSizeSeventyFivePercent:
709 mainWebView.getSettings().setTextZoom(75);
712 case R.id.fontSizeOneHundredPercent:
713 mainWebView.getSettings().setTextZoom(100);
716 case R.id.fontSizeOneHundredTwentyFivePercent:
717 mainWebView.getSettings().setTextZoom(125);
720 case R.id.fontSizeOneHundredFiftyPercent:
721 mainWebView.getSettings().setTextZoom(150);
724 case R.id.fontSizeOneHundredSeventyFivePercent:
725 mainWebView.getSettings().setTextZoom(175);
728 case R.id.fontSizeTwoHundredPercent:
729 mainWebView.getSettings().setTextZoom(200);
733 Intent shareIntent = new Intent();
734 shareIntent.setAction(Intent.ACTION_SEND);
735 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
736 shareIntent.setType("text/plain");
737 startActivity(Intent.createChooser(shareIntent, "Share URL"));
740 case R.id.addToHomescreen:
741 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
742 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
743 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
745 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
749 mainWebView.reload();
753 // Don't consume the event.
754 return super.onOptionsItemSelected(menuItem);
758 // removeAllCookies is deprecated, but it is required for API < 21.
759 @SuppressWarnings("deprecation")
761 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
762 int menuItemId = menuItem.getItemId();
764 switch (menuItemId) {
766 mainWebView.loadUrl(homepage, customHeaders);
770 if (mainWebView.canGoBack()) {
771 mainWebView.goBack();
776 if (mainWebView.canGoForward()) {
777 mainWebView.goForward();
782 // Launch BookmarksActivity.
783 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
784 startActivity(bookmarksIntent);
788 // Launch the system Download Manager.
789 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
791 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
792 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
794 startActivity(downloadManagerIntent);
798 // Launch `SettingsActivity`.
799 Intent settingsIntent = new Intent(this, SettingsActivity.class);
800 startActivity(settingsIntent);
804 // Launch `GuideActivity`.
805 Intent guideIntent = new Intent(this, GuideActivity.class);
806 startActivity(guideIntent);
810 // Launch `AboutActivity`.
811 Intent aboutIntent = new Intent(this, AboutActivity.class);
812 startActivity(aboutIntent);
815 case R.id.clearAndExit:
816 // Clear cookies. The commands changed slightly in API 21.
817 if (Build.VERSION.SDK_INT >= 21) {
818 cookieManager.removeAllCookies(null);
820 cookieManager.removeAllCookie();
823 // Clear DOM storage.
824 WebStorage domStorage = WebStorage.getInstance();
825 domStorage.deleteAllData();
828 WebViewDatabase formData = WebViewDatabase.getInstance(this);
829 formData.clearFormData();
831 // Clear cache. The argument of "true" includes disk files.
832 mainWebView.clearCache(true);
834 // Clear the back/forward history.
835 mainWebView.clearHistory();
837 // Clear any SSL certificate preferences.
838 mainWebView.clearSslPreferences();
840 // Clear `formattedUrlString`.
841 formattedUrlString = null;
843 // Clear `customHeaders`.
844 customHeaders.clear();
846 // Destroy the internal state of the webview.
847 mainWebView.destroy();
849 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
850 if (Build.VERSION.SDK_INT >= 21) {
851 finishAndRemoveTask();
861 // Close the navigation drawer.
862 drawerLayout.closeDrawer(GravityCompat.START);
867 public void onPostCreate(Bundle savedInstanceState) {
868 super.onPostCreate(savedInstanceState);
870 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
871 drawerToggle.syncState();
875 public void onConfigurationChanged(Configuration newConfig) {
876 super.onConfigurationChanged(newConfig);
878 // Reload the ad if this is the free flavor.
879 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
881 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
882 adView = findViewById(R.id.adView);
884 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug: https://code.google.com/p/android/issues/detail?id=20493#c8
885 invalidateOptionsMenu();
889 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
890 // Get shortcutNameEditText from the alert dialog.
891 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
893 // Create the bookmark shortcut based on formattedUrlString.
894 Intent bookmarkShortcut = new Intent();
895 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
896 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
898 // Place the bookmark shortcut on the home screen.
899 Intent placeBookmarkShortcut = new Intent();
900 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
901 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
902 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
903 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
904 sendBroadcast(placeBookmarkShortcut);
908 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
909 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
910 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
912 // Get the file name from `dialogFragment`.
913 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
914 String fileName = downloadFileNameEditText.getText().toString();
916 // Set the download save in the the `DIRECTORY_DOWNLOADS`using `fileName`.
917 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
918 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
920 // Allow `MediaScanner` to index the download if it is a media file.
921 downloadRequest.allowScanningByMediaScanner();
923 // Add the URL as the description for the download.
924 downloadRequest.setDescription(downloadUrl);
926 // Show the download notification after the download is completed.
927 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
929 // Initiate the download and display a Snackbar.
930 downloadManager.enqueue(downloadRequest);
933 public void viewSslCertificate(View view) {
934 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
935 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
936 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
940 public void onSslErrorCancel() {
941 sslErrorHandler.cancel();
945 public void onSslErrorProceed() {
946 sslErrorHandler.proceed();
949 // Override onBackPressed to handle the navigation drawer and mainWebView.
951 public void onBackPressed() {
952 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
954 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
955 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
956 drawerLayout.closeDrawer(GravityCompat.START);
958 // Load the previous URL if available.
959 if (mainWebView.canGoBack()) {
960 mainWebView.goBack();
962 // Pass onBackPressed to the system.
963 super.onBackPressed();
969 public void onPause() {
970 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
971 BannerAd.pauseAd(adView);
977 public void onResume() {
980 // We need to resume the adView for the free flavor.
981 BannerAd.resumeAd(adView);
985 public void onRestart() {
988 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
991 // Update the privacy icons.
992 updatePrivacyIcons();
996 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
997 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
998 String unformattedUrlString = urlTextBox.getText().toString().trim();
1000 URL unformattedUrl = null;
1001 Uri.Builder formattedUri = new Uri.Builder();
1003 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1004 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1005 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1006 if (!unformattedUrlString.startsWith("http")) {
1007 unformattedUrlString = "http://" + unformattedUrlString;
1010 // 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.
1012 unformattedUrl = new URL(unformattedUrlString);
1013 } catch (MalformedURLException e) {
1014 e.printStackTrace();
1017 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1018 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1019 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1020 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1021 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1022 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1024 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1025 formattedUrlString = formattedUri.build().toString();
1027 // Sanitize the search input and convert it to a DuckDuckGo search.
1028 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1030 // Use the correct search URL.
1031 if (javaScriptEnabled) { // JavaScript is enabled.
1032 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1033 } else { // JavaScript is disabled.
1034 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1038 mainWebView.loadUrl(formattedUrlString, customHeaders);
1040 // Hides the keyboard so we can see the webpage.
1041 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1042 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1045 private void applySettings() {
1046 // Get the shared preference values. `this` references the current context.
1047 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1049 // Store the values from `sharedPreferences` in variables.
1050 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
1051 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1052 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1053 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1054 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1055 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1056 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1057 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1058 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1059 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1060 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1062 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1063 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1064 // Get the values from `sharedPreferences`.
1065 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1066 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1067 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1068 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1069 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1071 // Apply the default settings.
1072 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1073 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1074 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1075 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1077 // Set third-party cookies status if API >= 21.
1078 if (Build.VERSION.SDK_INT >= 21) {
1079 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1083 // Apply the settings from `sharedPreferences`.
1084 homepage = homepageString;
1085 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1086 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1088 // Set the user agent initial status.
1089 switch (userAgentString) {
1090 case "Default user agent":
1091 // Set the user agent to `""`, which uses the default value.
1092 mainWebView.getSettings().setUserAgentString("");
1095 case "Custom user agent":
1096 // Set the custom user agent.
1097 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1101 // Use the selected user agent.
1102 mainWebView.getSettings().setUserAgentString(userAgentString);
1106 // Set JavaScript disabled search.
1107 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1108 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1109 } else { // Use the string from the pre-built list.
1110 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1113 // Set JavaScript enabled search.
1114 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1115 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1116 } else { // Use the string from the pre-built list.
1117 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1120 // Set Do Not Track status.
1121 if (doNotTrackEnabled) {
1122 customHeaders.put("DNT", "1");
1124 customHeaders.remove("DNT");
1127 // Set Orbot proxy status.
1128 if (proxyThroughOrbot) {
1129 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1130 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1131 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1132 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1136 private void updatePrivacyIcons() {
1137 // Get handles for the icons.
1138 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1139 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1140 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1141 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1143 // Update `privacyIcon`.
1144 if (javaScriptEnabled) { // JavaScript is enabled.
1145 privacyIcon.setIcon(R.drawable.javascript_enabled);
1146 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1147 privacyIcon.setIcon(R.drawable.warning);
1148 } else { // All the dangerous features are disabled.
1149 privacyIcon.setIcon(R.drawable.privacy_mode);
1152 // Update `firstPartyCookiesIcon`.
1153 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1154 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1155 } else { // First-party cookies are disabled.
1156 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1159 // Update `domStorageIcon`.
1160 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1161 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1162 } else if (javaScriptEnabled){ // JavaScript is enabled but DOM storage is disabled.
1163 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1164 } else { // JavaScript is disabled, so DOM storage is ghosted.
1165 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1168 // Update `formDataIcon`.
1169 if (saveFormDataEnabled) { // Form data is enabled.
1170 formDataIcon.setIcon(R.drawable.form_data_enabled);
1171 } else { // Form data is disabled.
1172 formDataIcon.setIcon(R.drawable.form_data_disabled);
1175 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1176 // `this` references the current activity.
1177 ActivityCompat.invalidateOptionsMenu(this);