List of usage examples for android.webkit WebView getSettings
public WebSettings getSettings()
From source file:com.facebook.react.views.webview.ReactWebViewManager.java
@ReactProp(name = "domStorageEnabled") public void setDomStorageEnabled(WebView view, boolean enabled) { view.getSettings().setDomStorageEnabled(enabled); }
From source file:com.facebook.react.views.webview.ReactWebViewManager.java
@ReactProp(name = "saveFormDataDisabled") public void setSaveFormDataDisabled(WebView view, boolean disable) { view.getSettings().setSaveFormData(!disable); }
From source file:com.facebook.react.views.webview.ReactWebViewManager.java
@ReactProp(name = "mediaPlaybackRequiresUserAction") public void setMediaPlaybackRequiresUserAction(WebView view, boolean requires) { view.getSettings().setMediaPlaybackRequiresUserGesture(requires); }
From source file:com.near.chimerarevo.fragments.CommentsFragment.java
@SuppressLint("SetJavaScriptEnabled") private void loadDisqusOAuth() { if (getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE) .getString(Constants.KEY_REFRESH_TOKEN, "").length() > 1) { RequestBody formBody = new FormEncodingBuilder().add("grant_type", "refresh_token") .add("client_id", Constants.DISQUS_API_KEY).add("client_secret", Constants.DISQUS_API_SECRET) .add("refresh_token", getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE) .getString(Constants.KEY_REFRESH_TOKEN, "")) .build();//from w w w. ja va 2s . com Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody).tag(FRAGMENT_TAG) .build(); if (mDialog == null) mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login); else mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login); mDialog.show(); OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback()); return; } final Dialog dialog = new Dialog(getActivity()); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.webview_layout); dialog.setCancelable(true); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { isDialogOpen = false; mFab.show(); } }); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface arg0) { isDialogOpen = false; mFab.show(); } }); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) CookieManager.getInstance().removeAllCookies(null); else { CookieSyncManager.createInstance(getActivity()); CookieManager.getInstance().removeAllCookie(); } WebView wv = (WebView) dialog.findViewById(R.id.webview); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setSaveFormData(false); wv.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); dialog.findViewById(R.id.progressContainer).setVisibility(View.GONE); dialog.findViewById(R.id.webViewContainer).setVisibility(View.VISIBLE); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); dialog.findViewById(R.id.progressContainer).setVisibility(View.VISIBLE); dialog.findViewById(R.id.webViewContainer).setVisibility(View.GONE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { boolean state = super.shouldOverrideUrlLoading(view, url); if (url.contains(Constants.SITE_URL)) { String code = url.split("code=")[1]; RequestBody formBody = new FormEncodingBuilder().add("grant_type", "authorization_code") .add("client_id", Constants.DISQUS_API_KEY) .add("client_secret", Constants.DISQUS_API_SECRET) .add("redirect_uri", Constants.SITE_URL).add("code", code).build(); Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody) .tag(FRAGMENT_TAG).build(); if (mDialog == null) mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login); else mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login); dialog.dismiss(); mDialog.show(); OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback()); } return state; } @Override public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) { handler.proceed(); } }); wv.loadUrl(URLUtils.getDisqusAuthUrl()); isDialogOpen = true; mFab.hide(); dialog.show(); }
From source file:net.bluecarrot.lite.MainActivity.java
private void setUpWebViewDefaults(WebView webView) { WebSettings settings = webView.getSettings(); //allow Geolocation settings.setGeolocationEnabled(savedPreferences.getBoolean("pref_allowGeolocation", true)); // Enable Javascript settings.setJavaScriptEnabled(true); //to make the webview faster //settings.setCacheMode(WebSettings.LOAD_NO_CACHE); // Use WideViewport and Zoom out if there is no viewport defined settings.setUseWideViewPort(true);/* ww w. j a v a 2 s . c o m*/ settings.setLoadWithOverviewMode(true); // better image sizing support settings.setSupportZoom(true); settings.setDisplayZoomControls(false); settings.setBuiltInZoomControls(true); settings.setGeolocationDatabasePath(getBaseContext().getFilesDir().getPath()); settings.setLoadsImagesAutomatically(!savedPreferences.getBoolean("pref_doNotDownloadImages", false));//to save data //todo setLoadsImagesAutomatically without restart the app // Enable pinch to zoom without the zoom buttons settings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { // Hide the zoom controls for HONEYCOMB+ settings.setDisplayZoomControls(false); } // Enable remote debugging via chrome://inspect if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } }
From source file:com.concentricsky.android.khanacademy.app.ShowProfileActivity.java
/** * Get the current user, and fail if there is none. *//*from w ww. j av a2 s .c o m*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); destroyed = false; this.webViewTimeoutPromptDialog = new AlertDialog.Builder(this) .setMessage("The page is taking a long time to respond. Stop loading?") .setPositiveButton("Stop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (webView != null) { webView.stopLoading(); finish(); } } }).setNegativeButton("Wait", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { stopWebViewLoadTimeout(); } }).setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { startWebViewLoadTimeout(); } }).create(); getActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.profile); setTitle(getString(R.string.profile_title)); webView = (WebView) findViewById(R.id.web_view); webView.setMinimumWidth(800); enableJavascript(webView); webView.getSettings().setDefaultZoom(ZoomDensity.FAR); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { Log.d(LOG_TAG, "shouldOverrideUrlLoading: " + url); URL parsed = null; try { parsed = new URL(url); } catch (MalformedURLException e) { // Let the webview figure that one out. return false; } // Only ka links will load in this webview. if (parsed.getHost().equals("www.khanacademy.org")) { // Video urls should link into video detail. See below for another video url format. if (parsed.getPath().equals("/video")) { String query = parsed.getQuery(); if (query != null && query.length() > 0) { String[] items = query.split("&"); String videoId = null; for (String item : items) { String[] parts = item.split("=", 2); if (parts.length > 1) { if ("v".equals(parts[0])) { videoId = parts[1]; break; } } } if (videoId != null) { String[] ids = normalizeVideoAndTopicId(videoId, ""); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } } // There was no ?v= or something weird is going on. Allow the page // load, which should hit KA's nice "no video found" page. showSpinner(); startWebViewLoadTimeout(); return false; } if (parsed.getPath().startsWith("/profile")) { // navigation within the profile makes sense here. showSpinner(); startWebViewLoadTimeout(); return false; } // Embedded logout option (in upper left menu) can be intercepted and cause the app to be logged out as well. if (parsed.getPath().equals("/logout")) { if (dataService != null) { dataService.getAPIAdapter().logout(); } finish(); return false; // try to let the webview hit logout to get the cookies cleared as we exit } // There is a new kind of video url now.. thanks guys.. // http://www.khanacademy.org/video/subtraction-2 // redirects to // http://www.khanacademy.org/math/arithmetic/addition-subtraction/two_dig_add_sub/v/subtraction-2 String[] path = parsed.getPath().split("/"); List<String> parts = Arrays.asList(path); if (parts.contains("v")) { String videoId = null; String topicId = null; for (int i = path.length - 1; i >= 0; --i) { if (path[i].equals("v")) { continue; } if (videoId == null) { videoId = path[i]; } else if (topicId == null) { topicId = path[i]; } else { break; } } if (videoId != null && topicId != null && dataService != null) { // Looks like a video url. Double check that we have the topic and video before launching detail activity. Log.d(LOG_TAG, "video and topic ids found; looks like a video url."); String[] ids = normalizeVideoAndTopicId(videoId, topicId); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } } else if (parsed.getPath().startsWith("/video")) { String videoId = path[path.length - 1]; String[] ids = normalizeVideoAndTopicId(videoId, ""); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } // showSpinner(); // startWebViewLoadTimeout(); // return false; } // All other urls should launch in the browser instead of here, except hash changes if we can distinguish. loadInBrowser(url); return true; } @Override public void onPageFinished(WebView view, String url) { Log.d(LOG_TAG, "onPageFinished"); stopWebViewLoadTimeout(); if (!destroyed) { hideSpinner(); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(LOG_TAG, "onPageStarted"); stopWebViewLoadTimeout(); // view.loadUrl("javascript:document.addEventListener( 'DOMContentLoaded',function() {AndroidApplication.jqueryReady()} );"); // handler.postDelayed(new Runnable() { // @Override // public void run() { // if (!destroyed) { // hijack(); // } // } // }, 100); } }); // webView.addJavascriptInterface(new Object() { // public void log(String msg) { // Log.d(LOG_TAG, "JSLOG: " + msg); // } // public void jqueryReady() { // Log.d(LOG_TAG, "javascript: jqueryReady"); // hijack(); // } // }, "AndroidApplication"); // showSpinner(); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService service) { dataService = service; api = service.getAPIAdapter(); String[] credentials = getCurrentLoginCredentials(); loginUser(credentials[0], credentials[1]); } }); }
From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java
private void addPasscodePreference(PreferenceGroup preferenceGroup) { final Context context = preferenceGroup.getContext(); PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context); passScreen.setTitle("4chan pass"); EditTextPreference passTokenPreference = new EditTextPreference(context); EditTextPreference passPINPreference = new EditTextPreference(context); Preference passLoginPreference = new Preference(context); Preference passClearPreference = new Preference(context); passTokenPreference.setTitle("Token"); passTokenPreference.setDialogTitle("Token"); passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN)); passTokenPreference.getEditText().setSingleLine(); passTokenPreference.getEditText()// w ww . j a va 2 s .c o m .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); passPINPreference.setTitle("PIN"); passPINPreference.setDialogTitle("PIN"); passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN)); passPINPreference.getEditText().setSingleLine(); passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER); passLoginPreference.setTitle("Log In"); passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (!useHttps()) Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show(); final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), ""); final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), ""); final String authUrl = "https://sys.4chan.org/auth"; //only https final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask(); final ProgressDialog passAuthProgressDialog = new ProgressDialog(context); passAuthProgressDialog.setMessage("Logging in"); passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { passAuthTask.cancel(); } }); passAuthProgressDialog.setCanceledOnTouchOutside(false); passAuthProgressDialog.show(); Async.runAsync(new Runnable() { @Override public void run() { try { if (passAuthTask.isCancelled()) return; setPasscodeCookie(null, true); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("act", "do_login")); pairs.add(new BasicNameValuePair("id", token)); pairs.add(new BasicNameValuePair("pin", pin)); HttpRequestModel request = HttpRequestModel.builder() .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build(); String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request, httpClient, null, passAuthTask, false); if (passAuthTask.isCancelled()) return; if (response.contains("Your device is now authorized")) { String passId = null; for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if (cookie.getName().equals("pass_id")) { String value = cookie.getValue(); if (!value.equals("0")) { passId = value; break; } } } if (passId == null) { showToast("Could not get pass id"); } else { setPasscodeCookie(passId, true); showToast("Success! Your device is now authorized."); } } else if (response.contains("Your Token must be exactly 10 characters")) { showToast("Incorrect token"); } else if (response.contains("You have left one or more fields blank")) { showToast("You have left one or more fields blank"); } else if (response.contains("Incorrect Token or PIN")) { showToast("Incorrect Token or PIN"); } else { Matcher m = Pattern .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>") .matcher(response); if (m.find()) { showToast(m.group(1)); } else { showWebView(response); } } } catch (Exception e) { showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown) : e.getMessage()); } finally { passAuthProgressDialog.dismiss(); } } private void showToast(final String message) { if (context instanceof Activity) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } }); } } private void showWebView(final String html) { if (context instanceof Activity) { ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { WebView webView = new WebView(context); webView.getSettings().setSupportZoom(true); webView.loadData(html, "text/html", null); new AlertDialog.Builder(context).setView(webView) .setNeutralButton(android.R.string.ok, null).show(); } }); } } }); return true; } }); passClearPreference.setTitle("Reset pass cookie"); passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { setPasscodeCookie(null, true); Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show(); return true; } }); passScreen.addPreference(passTokenPreference); passScreen.addPreference(passPINPreference); passScreen.addPreference(passLoginPreference); passScreen.addPreference(passClearPreference); preferenceGroup.addPreference(passScreen); }
From source file:io.selendroid.server.model.AndroidNativeElement.java
public JSONObject toJson() throws JSONException { JSONObject object = new JSONObject(); JSONObject l10n = new JSONObject(); l10n.put("matches", 0); object.put("l10n", l10n); CharSequence cd = getView().getContentDescription(); if (cd != null && cd.length() > 0) { String label = String.valueOf(cd); object.put("name", label); } else {/*from w w w . j a v a 2 s . c o m*/ object.put("name", ""); } String id = getNativeId(); object.put("id", id.startsWith("id/") ? id.replace("id/", "") : id); JSONObject rect = new JSONObject(); object.put("rect", rect); JSONObject origin = new JSONObject(); Point location = getLocation(); origin.put("x", location.x); origin.put("y", location.y); rect.put("origin", origin); JSONObject size = new JSONObject(); Dimension s = getSize(); size.put("height", s.getHeight()); size.put("width", s.getWidth()); rect.put("size", size); object.put("ref", ke.getIdOfElement(this)); object.put("type", getView().getClass().getSimpleName()); String value = ""; if (getView() instanceof TextView) { value = String.valueOf(((TextView) getView()).getText()); } object.put("value", value); object.put("shown", getView().isShown()); if (getView() instanceof WebView) { final WebView webview = (WebView) getView(); final WebViewSourceClient client = new WebViewSourceClient(); instrumentation.getCurrentActivity().runOnUiThread(new Runnable() { public void run() { synchronized (syncObject) { webview.getSettings().setJavaScriptEnabled(true); webview.setWebChromeClient(client); String script = "document.body.parentNode.innerHTML"; webview.loadUrl("javascript:alert('selendroidSource:'+" + script + ")"); } } }); long end = System.currentTimeMillis() + 10000; waitForDone(end, UI_TIMEOUT, "Error while grabbing web view source code."); object.put("source", "<html>" + client.result + "</html>"); } return object; }
From source file:org.openqa.selendroid.server.model.SelendroidWebDriver.java
private void configureWebView(final WebView view) { ServerInstrumentation.getInstance().runOnUiThread(new Runnable() { @Override// ww w. ja v a 2 s. c o m public void run() { view.clearCache(true); view.clearFormData(); view.clearHistory(); view.setFocusable(true); view.setFocusableInTouchMode(true); view.setNetworkAvailable(true); view.setWebChromeClient(new MyWebChromeClient()); WebSettings settings = view.getSettings(); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setSupportMultipleWindows(true); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); settings.setAppCacheEnabled(true); settings.setAppCacheMaxSize(10 * 1024 * 1024); settings.setAppCachePath(""); settings.setDatabaseEnabled(true); settings.setDomStorageEnabled(true); settings.setGeolocationEnabled(true); settings.setSaveFormData(false); settings.setSavePassword(false); settings.setRenderPriority(WebSettings.RenderPriority.HIGH); // Flash settings settings.setPluginState(WebSettings.PluginState.ON); // Geo location settings settings.setGeolocationEnabled(true); settings.setGeolocationDatabasePath("/data/data/selendroid"); } }); }
From source file:com.microsoft.windowsazure.mobileservices.LoginManager.java
/** * Creates the UI for the interactive authentication process * /*from w w w .j a v a 2s .co m*/ * @param provider * The provider used for the authentication process * @param startUrl * The initial URL for the authentication process * @param endUrl * The final URL for the authentication process * @param context * The context used to create the authentication dialog * @param callback * Callback to invoke when the authentication process finishes */ private void showLoginUI(final String startUrl, final String endUrl, final Context context, LoginUIOperationCallback callback) { if (startUrl == null || startUrl == "") { throw new IllegalArgumentException("startUrl can not be null or empty"); } if (endUrl == null || endUrl == "") { throw new IllegalArgumentException("endUrl can not be null or empty"); } if (context == null) { throw new IllegalArgumentException("context can not be null"); } final LoginUIOperationCallback externalCallback = callback; final AlertDialog.Builder builder = new AlertDialog.Builder(context); // Create the Web View to show the login page final WebView wv = new WebView(context); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (externalCallback != null) { externalCallback.onCompleted(null, new MobileServiceException("User Canceled")); } } }); wv.getSettings().setJavaScriptEnabled(true); DisplayMetrics displaymetrics = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int webViewHeight = displaymetrics.heightPixels; wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight)); wv.requestFocus(View.FOCUS_DOWN); wv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { if (!view.hasFocus()) { view.requestFocus(); } } return false; } }); // Create a LinearLayout and add the WebView to the Layout LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(wv); // Add a dummy EditText to the layout as a workaround for a bug // that prevents showing the keyboard for the WebView on some devices EditText dummyEditText = new EditText(context); dummyEditText.setVisibility(View.GONE); layout.addView(dummyEditText); // Add the layout to the dialog builder.setView(layout); final AlertDialog dialog = builder.create(); wv.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // If the URL of the started page matches with the final URL // format, the login process finished if (isFinalUrl(url)) { if (externalCallback != null) { externalCallback.onCompleted(url, null); } dialog.dismiss(); } super.onPageStarted(view, url, favicon); } // Checks if the given URL matches with the final URL's format private boolean isFinalUrl(String url) { if (url == null) { return false; } return url.startsWith(endUrl); } // Checks if the given URL matches with the start URL's format private boolean isStartUrl(String url) { if (url == null) { return false; } return url.startsWith(startUrl); } @Override public void onPageFinished(WebView view, String url) { if (isStartUrl(url)) { if (externalCallback != null) { externalCallback.onCompleted(null, new MobileServiceException( "Logging in with the selected authentication provider is not enabled")); } dialog.dismiss(); } } }); wv.loadUrl(startUrl); dialog.show(); }