Example usage for android.webkit WebView evaluateJavascript

List of usage examples for android.webkit WebView evaluateJavascript

Introduction

In this page you can find the example usage for android.webkit WebView evaluateJavascript.

Prototype

public void evaluateJavascript(String script, @Nullable ValueCallback<String> resultCallback) 

Source Link

Document

Asynchronously evaluates JavaScript in the context of the currently displayed page.

Usage

From source file:de.baumann.hhsmoodle.helper.helper_webView.java

public static void webView_WebViewClient(final Activity from, final SwipeRefreshLayout swipeRefreshLayout,
        final WebView webView) {

    webView.setWebViewClient(new WebViewClient() {

        ProgressDialog progressDialog;//from www  . j  a va 2  s .  co  m
        int numb;

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            ViewPager viewPager = (ViewPager) from.findViewById(R.id.viewpager);
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(from);
            sharedPref.edit().putString("loadURL", webView.getUrl()).apply();

            if (viewPager.getCurrentItem() == 0) {
                if (url != null) {
                    from.setTitle(webView.getTitle());
                }
            }

            if (url != null && url.contains("moodle.huebsch.ka.schule-bw.de/moodle/")
                    && url.contains("/login/")) {

                if (viewPager.getCurrentItem() == 0 && numb != 1) {
                    progressDialog = new ProgressDialog(from);
                    progressDialog.setTitle(from.getString(R.string.login_title));
                    progressDialog.setMessage(from.getString(R.string.login_text));
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                            from.getString(R.string.toast_settings), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    helper_main.switchToActivity(from, Activity_settings.class, true);
                                }
                            });
                    progressDialog.show();
                    numb = 1;
                    progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            numb = 0;
                        }
                    });
                }

            } else if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.cancel();
                numb = 0;
            }

            swipeRefreshLayout.setRefreshing(false);

            class_SecurePreferences sharedPrefSec = new class_SecurePreferences(from, "sharedPrefSec",
                    "Ywn-YM.XK$b:/:&CsL8;=L,y4", true);
            String username = sharedPrefSec.getString("username");
            String password = sharedPrefSec.getString("password");

            final String js = "javascript:" + "document.getElementById('password').value = '" + password + "';"
                    + "document.getElementById('username').value = '" + username + "';"
                    + "var ans = document.getElementsByName('answer');"
                    + "document.getElementById('loginbtn').click()";

            if (Build.VERSION.SDK_INT >= 19) {
                view.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
            } else {
                view.loadUrl(js);
            }
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return handleUri(uri);
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return handleUri(uri);
        }

        private boolean handleUri(final Uri uri) {
            Log.i(TAG, "Uri =" + uri);
            final String url = uri.toString();
            // Based on some condition you need to determine if you are going to load the url
            // in your web view itself or in a browser.
            // You can use `host` or `scheme` or any part of the `uri` to decide.

            if (url.startsWith("http"))
                return false;//open web links as usual
            //try to find browse activity to handle uri
            Uri parsedUri = Uri.parse(url);
            PackageManager packageManager = from.getPackageManager();
            Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
            if (browseIntent.resolveActivity(packageManager) != null) {
                from.startActivity(browseIntent);
                return true;
            }
            //if not activity found, try to parse intent://
            if (url.startsWith("intent:")) {
                try {
                    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    if (intent.resolveActivity(from.getPackageManager()) != null) {
                        from.startActivity(intent);
                        return true;
                    }
                    //try to find fallback url
                    String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                    if (fallbackUrl != null) {
                        webView.loadUrl(fallbackUrl);
                        return true;
                    }
                    //invite to install
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse("market://details?id=" + intent.getPackage()));
                    if (marketIntent.resolveActivity(packageManager) != null) {
                        from.startActivity(marketIntent);
                        return true;
                    }
                } catch (URISyntaxException e) {
                    //not an intent uri
                }
            }
            return true;//do nothing in other cases
        }
    });
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void trySetupContentView() {
    mContentView.setVerticalScrollBarEnabled(false);
    mContentView.setHorizontalScrollBarEnabled(false);
    mContentView.getSettings().setJavaScriptEnabled(true);

    mContentView.setWebChromeClient(new WebChromeClient() {
        @Override/*from   w  ww .ja v  a  2 s  . c  o m*/
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            Log.d(TAG, "newProgress = [" + newProgress + "]");
        }
    });

    mContentView.addJavascriptInterface(this, "Attiq");
    mContentView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (!mIsFirstTimeLoaded && mLoadingView != null) {
                mLoadingView.setAlpha(1.f);
                mLoadingView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            if (PrefUtil.isMathJaxEnabled()) {
                view.evaluateJavascript("javascript:document.getElementById('content').innerHTML='"
                        + doubleEscapeTeX(mArticle.getRenderedBody()) + "';", null);
                view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);",
                        new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                view.loadUrl("javascript:(function () "
                                        + "{document.getElementsByTagName('body')[0].style.marginBottom = '0'})()");
                            }
                        });
            }

            mIsFirstTimeLoaded = true;
            if (mLoadingView != null) {
                ViewCompat.animate(mLoadingView).alpha(0.f).setDuration(300)
                        .setListener(new ViewPropertyAnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(View view) {
                                if (mLoadingView != null) {
                                    mLoadingView.setVisibility(View.GONE);
                                }
                            }
                        }).start();
            }
        }
    });

    mContentView.setFindListener(new WebView.FindListener() {
        @Override
        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
            if (mMenuLayout != null) {
                mMenuLayout.closeDrawer(GravityCompat.END);
            }
            if (numberOfMatches > 0 && mMenuAnchor != null && mContentView != null) {
                // FIXME Doesn't work now, because WebView is staying inside ScrollView
                mContentView.loadUrl("javascript:scrollToElement(\"" + mMenuAnchor.text() + "\");");
            }
        }
    });
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private void execJSUnsafe(WebView web, String js) {
    if (useEvaluateJavascript()) {
        web.evaluateJavascript(js, null);
    } else {/*  w  ww . j a  v  a 2 s  .  c  o  m*/
        web.loadUrl("javascript:(function(){" + js + "})()");
    }
}