List of usage examples for android.webkit WebView evaluateJavascript
public void evaluateJavascript(String script, @Nullable ValueCallback<String> resultCallback)
From source file:Main.java
public static void runJavascriptOnWebView(WebView webview, String js) { // before Kitkat, the only way to run javascript was to load a url that starts with "javascript:". // Starting in Kitkat, the "javascript:" method still works, but it expects the rest of the string // to be URL encoded, unlike previous versions. Rather than URL encode for Kitkat and above, // use the new evaluateJavascript method. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { webview.loadUrl("javascript:" + js); } else {/*from w w w .ja va 2 s .c o m*/ webview.evaluateJavascript(js, null); } }
From source file:com.mario22gmail.license.nfc_project.FragmentBrowser.java
public void OpenWebSite(String urlFromCredential, String javaScript) { mWebview.loadUrl(urlFromCredential); WebSettings settings = mWebview.getSettings(); settings.setJavaScriptEnabled(true); urlEditText.setText(urlFromCredential); final String javaScriptFinal = javaScript; final String urlFromCredentialFinal = urlFromCredential; mWebview.setWebViewClient(new WebViewClient() { @Override//from w ww . j a v a 2 s . c o m public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (url.startsWith(urlFromCredentialFinal)) { if (Build.VERSION.SDK_INT >= 19) { view.evaluateJavascript(javaScriptFinal, new ValueCallback<String>() { @Override public void onReceiveValue(String s) { } }); } else { view.loadUrl(javaScriptFinal); } } } }); }
From source file:org.mozilla.focus.webkit.FocusWebViewClient.java
@Override public void onLoadResource(WebView view, String url) { // We can't access the webview during shouldInterceptRequest(), however onLoadResource() // is called on the UI thread so we're allowed to do this now: view.evaluateJavascript("(function() {" + "function cleanupVisited() {" + CLEAR_VISITED_CSS + "}" + // Add an onLoad() listener so that we run the cleanup script every time // a <link>'d css stylesheet is loaded: "let links = document.getElementsByTagName('link');" + "for (i = 0; i < links.length; i++) {" + " link = links[i];" + " if (link.rel == 'stylesheet') {" + " link.addEventListener('load', cleanupVisited, false);" + " }" + "}" + "})();", null);//w w w . jav a 2s. c om super.onLoadResource(view, url); }
From source file:de.uni_weimar.m18.anatomiederstadt.element.LatexFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_latex, container, false); WebView latexView = (WebView) root.findViewById(R.id.latexWebView); latexView.getSettings().setJavaScriptEnabled(true); latexView.getSettings().setBuiltInZoomControls(false); TypedValue typedValue = new TypedValue(); Resources.Theme theme = getActivity().getTheme(); theme.resolveAttribute(R.color.windowBackgroundColor, typedValue, true); latexView.setBackgroundColor(typedValue.data); latexView.loadDataWithBaseURL("http://bar", "<script type='text/x-mathjax-config'>" + "MathJax.Hub.Config({ " + "messageStyle: 'none'," + "showMathMenu: false, " + "jax: ['input/TeX','output/HTML-CSS'], " + "extensions: ['tex2jax.js'], " + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js'," + "'noErrors.js','noUndefined.js'] } " + "});</script>" + "<script type='text/javascript' " + "src='file:///android_asset/MathJax/MathJax.js'" + "></script><span id='math'></span>", "text/html", "utf-8", ""); Log.v(LOG_TAG, "Loading latexCode: " + mLatexCode); latexView.setWebViewClient(new WebViewClient() { private String mLatexCode = null; @Override//w w w. j a v a2 s . c o m public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (Build.VERSION.SDK_INT < 19) { view.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\[" + doubleEscapeTeX(getLatexCode()) + "\\\\]'"); view.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);"); } else { view.evaluateJavascript("javascript:document.getElementById('math').innerHTML='\\\\[" + doubleEscapeTeX(getLatexCode()) + "\\\\]'", null); view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);", null); } } }); return root; }
From source file:net.basov.ticketinfo.UI.java
public void displayHelpScreen(String title, final WebView wv) { setHelp("h_header", title); setHelp("h_storage", FileIO.getFilesDir(wv.getContext()).getAbsolutePath()); wv.setWebViewClient(new MyWebViewClient() { @Override/*from w w w . j a v a2 s . co m*/ public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + help_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + help_json.toString() + "')"); } wv.clearCache(true); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.help_ui_file)); }
From source file:net.basov.ticketinfo.UI.java
public void displayMainScreen(final WebView wv) { wv.setWebViewClient(new MyWebViewClient() { @Override/*from w w w. j a v a2s .c om*/ public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + header_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + ticket_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + ic_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + dump_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + header_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + ticket_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + ic_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + dump_json.toString() + "')"); } wv.clearCache(true); wv.clearHistory(); //TODO: remove debug //Log.d("hhhh", header_json.toString()); //Log.d("tttt", ticket_json.toString()); //Log.d("iiii", ic_json.toString()); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.ticket_ui_file)); }
From source file:net.basov.ticketinfo.UI.java
public void displayWelcomeScreen(final WebView wv) { SharedPreferences defSharedPref = PreferenceManager.getDefaultSharedPreferences(wv.getContext()); setWelcome("s_lang", defSharedPref.getString(wv.getContext().getString(R.string.pk_app_lang), wv.getContext().getString(R.string.pref_lang_def))); if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_transliterate_flag), false)) { setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else {//from w ww.j a va2 s . com setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\">"); } if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_send_platform_info), true)) { setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else { setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\">"); } if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_use_view_directory), false)) { setWelcome("s_use_view_directory", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">"); } else { setWelcome("s_use_view_directory", "<input type=\"checkbox\" disabled=\"disabled\">"); } wv.setWebViewClient(new MyWebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + welcome_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + welcome_json.toString() + "')", null); } wv.clearCache(true); wv.clearHistory(); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.welcome_ui_file)); }
From source file:org.mozilla.focus.webkit.FocusWebViewClient.java
@Override public void onPageFinished(WebView view, final String url) { if (callback != null) { callback.onPageFinished(view.getCertificate() != null); // The URL which is supplied in onPageFinished() could be fake (see #301), but webview's // URL is always correct _except_ for error pages final String viewURL = view.getUrl(); if (!UrlUtils.isInternalErrorURL(viewURL)) { callback.onURLChanged(view.getUrl()); }// w w w . j av a2 s . c om } super.onPageFinished(view, url); view.evaluateJavascript("(function() {" + CLEAR_VISITED_CSS + "})();", null); }
From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java
public void OpenFacebook(String userName, String password) { WebView mWebview = (WebView) findViewById(R.id.webViewFb); String url = "https://www.facebook.com"; js = "javascript:document.getElementsByName('email')[0].value = '" + userName + "';document.getElementsByName('pass')[0].value='" + password + "';document.getElementsByName('login')[0].click();"; mWebview.loadUrl(url);/*ww w . j a va 2s . c o m*/ WebSettings settings = mWebview.getSettings(); settings.setJavaScriptEnabled(true); mWebview.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (Build.VERSION.SDK_INT >= 19) { view.evaluateJavascript(js, new ValueCallback<String>() { @Override public void onReceiveValue(String s) { } }); } else { view.loadUrl(js); } } }); }
From source file:com.anjalimacwan.fragment.NoteViewFragment.java
@SuppressLint("SetJavaScriptEnabled") @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override//from w w w. j a v a 2 s .c o m public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Set values setRetainInstance(true); setHasOptionsMenu(true); // Get filename of saved note filename = getArguments().getString("filename"); // Change window title String title; try { title = listener.loadNoteTitle(filename); } catch (IOException e) { title = getResources().getString(R.string.view_note); } getActivity().setTitle(title); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null, ContextCompat.getColor(getActivity(), R.color.primary)); getActivity().setTaskDescription(taskDescription); } // Show the Up button in the action bar. ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Animate elevation change if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LinearLayout noteViewEdit = (LinearLayout) getActivity().findViewById(R.id.noteViewEdit); LinearLayout noteList = (LinearLayout) getActivity().findViewById(R.id.noteList); noteList.animate().z(0f); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) noteViewEdit.animate() .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land)); else noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation)); } // Set up content view TextView noteContents = (TextView) getActivity().findViewById(R.id.textView); markdownView = (MarkdownView) getActivity().findViewById(R.id.markdownView); // Apply theme SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE); ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrollView); String theme = pref.getString("theme", "light-sans"); int textSize = -1; int textColor = -1; String fontFamily = null; if (theme.contains("light")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary)); noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (markdownView != null) { markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (theme.contains("dark")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark)); noteContents .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (markdownView != null) { markdownView .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (theme.contains("sans")) { if (noteContents != null) noteContents.setTypeface(Typeface.SANS_SERIF); if (markdownView != null) fontFamily = "sans-serif"; } if (theme.contains("serif")) { if (noteContents != null) noteContents.setTypeface(Typeface.SERIF); if (markdownView != null) fontFamily = "serif"; } if (theme.contains("monospace")) { if (noteContents != null) noteContents.setTypeface(Typeface.MONOSPACE); if (markdownView != null) fontFamily = "monospace"; } switch (pref.getString("font_size", "normal")) { case "smallest": textSize = 12; break; case "small": textSize = 14; break; case "normal": textSize = 16; break; case "large": textSize = 18; break; case "largest": textSize = 20; break; } if (noteContents != null) noteContents.setTextSize(textSize); if (markdownView != null) { String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom) / getResources().getDisplayMetrics().density) + "px"; String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right) / getResources().getDisplayMetrics().density) + "px"; String fontSize = " " + Integer.toString(textSize) + "px"; String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff"); final String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}"; final String js = "var styleNode = document.createElement('style');\n" + "styleNode.type = \"text/css\";\n" + "var styleText = document.createTextNode('" + css + "');\n" + "styleNode.appendChild(styleText);\n" + "document.getElementsByTagName('head')[0].appendChild(styleNode);\n"; markdownView.getSettings().setJavaScriptEnabled(true); markdownView.getSettings().setLoadsImagesAutomatically(false); markdownView.setWebViewClient(new WebViewClient() { @TargetApi(Build.VERSION_CODES.N) @Override public void onLoadResource(WebView view, String url) { view.stopLoading(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) try { startActivity(intent); } catch (ActivityNotFoundException | FileUriExposedException e) { /* Gracefully fail */ } else try { startActivity(intent); } catch (ActivityNotFoundException e) { /* Gracefully fail */ } } @Override public void onPageFinished(WebView view, String url) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) view.evaluateJavascript(js, null); else view.loadUrl("javascript:" + js); } }); } // Load note contents try { contentsOnLoad = listener.loadNote(filename); } catch (IOException e) { showToast(R.string.error_loading_note); // Add NoteListFragment or WelcomeFragment Fragment fragment; if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal")) fragment = new NoteListFragment(); else fragment = new WelcomeFragment(); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit(); } // Set TextView contents if (noteContents != null) noteContents.setText(contentsOnLoad); if (markdownView != null) markdownView.loadMarkdown(contentsOnLoad); // Show a toast message if this is the user's first time viewing a note final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); firstLoad = sharedPref.getInt("first-load", 0); if (firstLoad == 0) { // Show dialog with info DialogFragment firstLoad = new FirstViewDialogFragment(); firstLoad.show(getFragmentManager(), "firstloadfragment"); // Set first-load preference to 1; we don't need to show the dialog anymore SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("first-load", 1); editor.apply(); } // Detect single and double-taps using GestureDetector final GestureDetector detector = new GestureDetector(getActivity(), new GestureDetector.OnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } }); detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onDoubleTap(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true)) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean("show_double_tap_message", false); editor.apply(); } Bundle bundle = new Bundle(); bundle.putString("filename", filename); Fragment fragment = new NoteEditFragment(); fragment.setArguments(bundle); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment") .commit(); return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) { showToastLong(R.string.double_tap); showMessage = false; } return false; } }); if (noteContents != null) noteContents.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return false; } }); if (markdownView != null) markdownView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return false; } }); }