android.webkit.WebView#evaluateJavascript ( )源码实例Demo

下面列出了android.webkit.WebView#evaluateJavascript ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: browser   文件: LightningView.java
@Override
public void onPageFinished(WebView view, String url) {
	if (view.isShown()) {
		mBrowserController.updateUrl(url, true);
		view.postInvalidate();
	}
	if (view.getTitle() == null || view.getTitle().isEmpty()) {
		mTitle.setTitle(mActivity.getString(R.string.untitled));
	} else {
		mTitle.setTitle(view.getTitle());
	}
	if (API >= android.os.Build.VERSION_CODES.KITKAT && mInvertPage) {
		view.evaluateJavascript(Constants.JAVASCRIPT_INVERT_PAGE, null);
	}
	mBrowserController.update();
}
 
源代码2 项目: Xndroid   文件: LightningWebClient.java
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onPageFinished(@NonNull WebView view, String url) {
    if (view.isShown()) {
        mUIController.updateUrl(url, false);
        mUIController.setBackButtonEnabled(view.canGoBack());
        mUIController.setForwardButtonEnabled(view.canGoForward());
        view.postInvalidate();
    }
    if (view.getTitle() == null || view.getTitle().isEmpty()) {
        mLightningView.getTitleInfo().setTitle(mActivity.getString(R.string.untitled));
    } else {
        mLightningView.getTitleInfo().setTitle(view.getTitle());
    }
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT &&
        mLightningView.getInvertePage()) {
        view.evaluateJavascript(Constants.JAVASCRIPT_INVERT_PAGE, null);
    }
    mUIController.tabChanged(mLightningView);
}
 
源代码3 项目: webTube   文件: WebTubeChromeClient.java
public void onProgressChanged(WebView view, int percentage) {
    progress.setVisibility(View.VISIBLE);
    progress.setProgress(percentage);

    // For more advanced loading status
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        progress.setIndeterminate(percentage == 100);
        view.evaluateJavascript("(function() { return document.readyState == \"complete\"; })();",
                value -> {
                    if (value.equals("true")) {
                        progress.setVisibility(View.INVISIBLE);
                    } else {
                        onProgressChanged(webView, 100);
                    }
                });
    } else {
        if (percentage == 100) {
            progress.setVisibility(View.GONE);
        }
    }
}
 
源代码4 项目: webTube   文件: WebTubeChromeClient.java
public void onProgressChanged(WebView view, int percentage) {
    progress.setVisibility(View.VISIBLE);
    progress.setProgress(percentage);

    // For more advanced loading status
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        progress.setIndeterminate(percentage == 100);
        view.evaluateJavascript("(function() { return document.readyState == \"complete\"; })();",
                value -> {
                    if (value.equals("true")) {
                        progress.setVisibility(View.INVISIBLE);
                    } else {
                        onProgressChanged(webView, 100);
                    }
                });
    } else {
        if (percentage == 100) {
            progress.setVisibility(View.GONE);
        }
    }
}
 
源代码5 项目: JumpGo   文件: LightningWebClient.java
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onPageFinished(@NonNull WebView view, String url) {
    if (view.isShown()) {
        mUIController.updateUrl(url, false);
        mUIController.setBackButtonEnabled(view.canGoBack());
        mUIController.setForwardButtonEnabled(view.canGoForward());
        view.postInvalidate();
    }
    if (view.getTitle() == null || view.getTitle().isEmpty()) {
        mLightningView.getTitleInfo().setTitle(mActivity.getString(R.string.untitled));
    } else {
        mLightningView.getTitleInfo().setTitle(view.getTitle());
    }
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT &&
        mLightningView.getInvertePage()) {
        view.evaluateJavascript(Constants.JAVASCRIPT_INVERT_PAGE, null);
    }
    mUIController.tabChanged(mLightningView);
}
 
源代码6 项目: NoiseCapture   文件: ViewHtmlPage.java
private void runJs() {
    final WebView webView = (WebView) findViewById(R.id.webview);
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    // Load extra parameters
    String versionInfo = "";
    try {
        versionInfo = getVersionString(ViewHtmlPage.this);
    } catch (PackageManager.NameNotFoundException ex){
        MAINLOGGER.error(ex.getLocalizedMessage(), ex);
    }
    String uuid = sharedPref.getString(MeasurementExport.PROP_UUID, "");
    String content = "<h1>"+getText(R.string.app_name)+"</h1> "+versionInfo+"<br/>"+getText(R.string.user_id_activity_about)+": "+uuid;
    String js = "document.getElementById(\"about_title\").innerHTML = \""+content+"\"";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript(js, null);
    } else {
        webView.loadUrl("javascript:"+js);
    }
}
 
源代码7 项目: v9porn   文件: PlayVideoPresenter.java
/**
 * 需要在UI线程执行
 * 借助webView, 动态加载md5.js,传入相关的参数也是可用解析得到地址
 *
 * @param mWebView webView
 */
private void decodeUrl(WebView mWebView) {
    String a = "MXoqQlMPfiwrPSYKNCFiWwVRCldRCgZffBdgKTZzBiYiNlU/IgcMQXwuPU8CT2FbLAkTS3hVGAQoHjEQOSFzQBYCKFwOfStgHCECTmZyMhg+YXovMAwdEjw6Lw8GVzQmDBAMIjYSPAsnHQ1YJTUjLx0gTFQFCScoIQQ9RgIlD0wLf3EIbAY9BCF2d0cvcQcf";
    String b = "a2d47W4FqndpWL/bOcbg5BGi0nXQy7SSoL2JoSA41zp8N6X/OMB14/UsfdVgtHF4uFysmNzYKtez57ZIkSKFTKKEfVuUbgXJZGdVcAfgwIHikanWSt+eKMrFhLosabZuAL+x6AkrmDF0";
    //Javascript返回add()函数的计算结果。
    mWebView.evaluateJavascript("parserVideoUrl('" + a + "','" + b + "')", value -> {
        Logger.t(TAG).d(value);
        if (TextUtils.isEmpty(value)) {
            return;
        }
        Document source = Jsoup.parse(value.replace("\\u003C", "<"));
        String videoUrl = source.select("source").first().attr("src");
        Logger.t(TAG).d(videoUrl);
    });
}
 
源代码8 项目: v9porn   文件: PlayVideoPresenter.java
/**
 * 需要在UI线程执行
 * 借助webView, 动态加载md5.js,传入相关的参数也是可用解析得到地址
 *
 * @param mWebView webView
 */
private void decodeUrl(WebView mWebView) {
    String a = "MXoqQlMPfiwrPSYKNCFiWwVRCldRCgZffBdgKTZzBiYiNlU/IgcMQXwuPU8CT2FbLAkTS3hVGAQoHjEQOSFzQBYCKFwOfStgHCECTmZyMhg+YXovMAwdEjw6Lw8GVzQmDBAMIjYSPAsnHQ1YJTUjLx0gTFQFCScoIQQ9RgIlD0wLf3EIbAY9BCF2d0cvcQcf";
    String b = "a2d47W4FqndpWL/bOcbg5BGi0nXQy7SSoL2JoSA41zp8N6X/OMB14/UsfdVgtHF4uFysmNzYKtez57ZIkSKFTKKEfVuUbgXJZGdVcAfgwIHikanWSt+eKMrFhLosabZuAL+x6AkrmDF0";
    //Javascript返回add()函数的计算结果。
    mWebView.evaluateJavascript("parserVideoUrl('" + a + "','" + b + "')", value -> {
        Logger.t(TAG).d(value);
        if (TextUtils.isEmpty(value)) {
            return;
        }
        Document source = Jsoup.parse(value.replace("\\u003C", "<"));
        String videoUrl = source.select("source").first().attr("src");
        Logger.t(TAG).d(videoUrl);
    });
}
 
源代码9 项目: GeneratePicture   文件: WebViewHelper.java
public void getSelectedData(WebView webView) {
//        String js = "(function getSelectedText() {" +
//                "var txt;" +
//                "if (window.getSelection) {" +
//                "txt = window.getSelection().toString();" +
//                "} else if (window.document.getSelection) {" +
//                "txt = window.document.getSelection().toString();" +
//                "} else if (window.document.selection) {" +
//                "txt = window.document.selection.createRange().text;" +
//                "}" +
//                "JSInterface.getText(txt);" +
//                "})()";

        String js = "(function getSelectedText() {" +
                "var txt;" +
                "if (window.getSelection) {" +
                "var range=window.getSelection().getRangeAt(0);" +
                "var container = window.document.createElement('div');" +
                "container.appendChild(range.cloneContents());" +
                "txt = container.innerHTML;" +
                "} else if (window.document.getSelection) {" +
                "var range=window.getSelection().getRangeAt(0);" +
                "var container = window.document.createElement('div');" +
                "container.appendChild(range.cloneContents());" +
                "txt = container.innerHTML;" +
                "} else if (window.document.selection) {" +
                "txt = window.document.selection.createRange().htmlText;" +
                "}" +
                "JSInterface.getText(txt);" +
                "})()";

        // calling the js function
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:" + js, null);
        } else {
            webView.loadUrl("javascript:" + js);
        }
        webView.clearFocus();
    }
 
源代码10 项目: focus-android   文件: 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:
            "var links = document.getElementsByTagName('link');" +
            "for (i = 0; i < links.length; i++) {" +
            "  link = links[i];" +
            "  if (link.rel == 'stylesheet') {" +
            "    link.addEventListener('load', cleanupVisited, false);" +
            "  }" +
            "}" +

            "})();",

            null);

    super.onLoadResource(view, url);
}
 
源代码11 项目: webTube   文件: WebTubeWebViewClient.java
public void onLoadResource(WebView view, String url) {
    if (!url.contains(".jpg") && !url.contains(".ico") && !url.contains(".css") && !url.contains(".js") && !url.contains("complete/search")) {
        // Remove all iframes (to prevent WebRTC exploits)
        view.loadUrl("javascript:(function() {" +
                "var iframes = document.getElementsByTagName('iframe');" +
                "for(i=0;i<=iframes.length;i++){" +
                "if(typeof iframes[0] != 'undefined')" +
                "iframes[0].outerHTML = '';" +
                "}})()");

        // Gets rid of orange outlines
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            String css = "*, *:focus { " +
                    " outline: none !important; -webkit-tap-highlight-color: rgba(255,255,255,0) !important; -webkit-tap-highlight-color: transparent !important; }" +
                    " ._mfd { padding-top: 2px !important; } ";
            view.loadUrl("javascript:(function() {" +
                    "if(document.getElementById('webTubeStyle') == null){" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var style = document.createElement('style');" +
                    "style.id = 'webTubeStyle';" +
                    "style.type = 'text/css';" +
                    "style.innerHTML = '" + css + "';" +
                    "parent.appendChild(style);" +
                    "}})()");
        }

        // To adapt the statusbar color
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            statusBarSpace.setVisibility(View.VISIBLE);
            view.evaluateJavascript("(function() { if(document.getElementById('player').style.visibility == 'hidden' || document.getElementById('player').innerHTML == '') { return 'not_video'; } else { return 'video'; } })();",
                    value -> {
                        int colorId = value.contains("not_video") ? R.color.colorPrimary : R.color.colorWatch;
                        statusBarSpace.setBackgroundColor(ContextCompat.getColor(context, colorId));
                        bottomBar.setBackgroundColor(ContextCompat.getColor(context, colorId));
                    });
        }
    }
}
 
源代码12 项目: webTube   文件: WebTubeWebViewClient.java
public void onLoadResource(WebView view, String url) {
    if (!url.contains(".jpg") && !url.contains(".ico") && !url.contains(".css") && !url.contains(".js") && !url.contains("complete/search")) {
        // Remove all iframes (to prevent WebRTC exploits)
        view.loadUrl("javascript:(function() {" +
                "var iframes = document.getElementsByTagName('iframe');" +
                "for(i=0;i<=iframes.length;i++){" +
                "if(typeof iframes[0] != 'undefined')" +
                "iframes[0].outerHTML = '';" +
                "}})()");

        // Gets rid of orange outlines
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            String css = "*, *:focus { " +
                    " outline: none !important; -webkit-tap-highlight-color: rgba(255,255,255,0) !important; -webkit-tap-highlight-color: transparent !important; }" +
                    " ._mfd { padding-top: 2px !important; } ";
            view.loadUrl("javascript:(function() {" +
                    "if(document.getElementById('webTubeStyle') == null){" +
                    "var parent = document.getElementsByTagName('head').item(0);" +
                    "var style = document.createElement('style');" +
                    "style.id = 'webTubeStyle';" +
                    "style.type = 'text/css';" +
                    "style.innerHTML = '" + css + "';" +
                    "parent.appendChild(style);" +
                    "}})()");
        }

        // To adapt the statusbar color
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            statusBarSpace.setVisibility(View.VISIBLE);
            view.evaluateJavascript("(function() { if(document.getElementById('player').style.visibility == 'hidden' || document.getElementById('player').innerHTML == '') { return 'not_video'; } else { return 'video'; } })();",
                    value -> {
                        int colorId = value.contains("not_video") ? R.color.colorPrimary : R.color.colorWatch;
                        statusBarSpace.setBackgroundColor(ContextCompat.getColor(context, colorId));
                        bottomBar.setBackgroundColor(ContextCompat.getColor(context, colorId));
                    });
        }
    }
}
 
源代码13 项目: GoldenGate   文件: JavaScriptBridge.java
@TargetApi(Build.VERSION_CODES.KITKAT)
protected static void evaluateJavascript(WebView webView, String javascript) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript(javascript, null);
    } else  {
        webView.loadUrl("javascript:" + javascript);
    }
}
 
源代码14 项目: utexas-utilities   文件: DataUsageActivity.java
@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    String jsScript = "window.ututilities.setUsageData(data.bytes_in, data.bytes_total, data.timestamp)";
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
        view.evaluateJavascript(jsScript, null);
    } else {
        // exec js
        if (!url.contains("javascript:")) {
            view.loadUrl("javascript:" + jsScript);
        }
    }
}
 
源代码15 项目: mobile-sdk-android   文件: ANJAMImplementation.java
private static void injectJavaScript(String url, WebView webView) {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(url, null);
        } else {
            webView.loadUrl(url);
        }
    } catch (Exception exception) {
        // We can't do anything much here if there is an exception ignoring.
        // This is to avoid crash of users app gracefully.
        Clog.e(Clog.baseLogTag, "ANJAMImplementation.loadResult -- Caught EXCEPTION...", exception);
        Clog.e(Clog.baseLogTag, "ANJAMImplementation.loadResult -- ...Recovering with webView.loadUrl.");
    }
}
 
源代码16 项目: Android-VimeoPlayer   文件: VimeoPlayer.java
@SuppressLint("SetJavaScriptEnabled")
private void initWebView(boolean enabledCache, JsBridge jsBridge, VimeoOptions vimeoOptions, int videoId, String hashKey, String baseUrl) {
    this.getSettings().setJavaScriptEnabled(true);
    this.getSettings().setSupportMultipleWindows(false);
    this.getSettings().setMediaPlaybackRequiresUserGesture(false);

    if (enabledCache) {
        this.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        this.getSettings().setDatabaseEnabled(true);
        this.getSettings().setDomStorageEnabled(true);
        this.getSettings().setAllowFileAccess(true);
        this.getSettings().setAppCacheEnabled(true);
        this.getSettings().setAppCachePath(this.getContext().getCacheDir().getAbsolutePath());
    } else {
        this.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        this.getSettings().setDatabaseEnabled(false);
        this.getSettings().setDomStorageEnabled(false);
        this.getSettings().setAllowFileAccess(false);
        this.getSettings().setAppCacheEnabled(false);
    }

    this.addJavascriptInterface(jsBridge, "JsBridge");
    final String unformattedString = readVimeoPlayerHTMLFromFile();
    String videoUrl = "https://vimeo.com/" + videoId;
    if (hashKey != null) {
        videoUrl += "/" + hashKey;
    }

    boolean autoPlay = false;
    if (!vimeoOptions.originalControls) {
        autoPlay = false;
    } else {
        autoPlay = vimeoOptions.autoPlay;
    }

    final String formattedString = unformattedString
            .replace("<VIDEO_URL>", videoUrl)
            .replace("<AUTOPLAY>", String.valueOf(autoPlay))
            .replace("<LOOP>", String.valueOf(vimeoOptions.loop))
            .replace("<MUTED>", String.valueOf(vimeoOptions.muted))
            .replace("<PLAYSINLINE>", String.valueOf(vimeoOptions.originalControls))
            .replace("<TITLE>", String.valueOf(vimeoOptions.title))
            .replace("<COLOR>", Utils.colorToHex(vimeoOptions.color))
            .replace("<BACKGROUND_COLOR>", Utils.colorToHex(vimeoOptions.backgroundColor))
            .replace("<QUALITY>", vimeoOptions.quality);


    this.loadDataWithBaseURL(baseUrl, formattedString, "text/html", "utf-8", null);

    // if the video's thumbnail is not in memory, show a black screen
    this.setWebChromeClient(new WebChromeClient() {
        @Override
        public Bitmap getDefaultVideoPoster() {
            Bitmap result = super.getDefaultVideoPoster();

            if (result == null)
                return Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
            else
                return result;
        }
    });

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView webView, String url) {
            webView.evaluateJavascript("javascript:initVimeoPlayer()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {

                }
            });
        }
    };
    setWebViewClient(webViewClient);
}
 
源代码17 项目: focus-android   文件: FocusWebViewClient.java
@Override
public void onPageFinished(WebView view, final String url) {
    SslCertificate certificate = view.getCertificate();
    shouldReadURL = true;

    if (!TextUtils.isEmpty(restoredUrl)) {
        if (restoredUrl.equals(url) && certificate == null) {
            // We just restored the previous state. Let's re-use the certificate we restored.
            // The reason for that is that WebView doesn't restore the certificate itself.
            // Without restoring the certificate manually we'd lose the certificate when
            // switching tabs or restoring a previous session for other reasons.
            certificate = restoredCertificate;
        } else {
            // The URL has changed since we restored the last state. Let's just clear all
            // restored data because we do not need it anymore.
            restoredUrl = null;
            restoredCertificate = null;
        }
    }

    if (callback != null) {
        // The page is secure when the url is a localized content or when the certificate isn't null
        final boolean isSecure = certificate != null || UrlUtils.isLocalizedContent(view.getUrl());

        callback.onPageFinished(isSecure);

        String host = null;
        try {
            host = new URI(url).getHost();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        callback.onSecurityChanged(isSecure, host, (certificate != null) ? certificate.getIssuedBy().getOName() : 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) && viewURL != null) {
            callback.onURLChanged(viewURL);
        }
    }
    super.onPageFinished(view, url);

    view.evaluateJavascript(
            "(function() {" +

            CLEAR_VISITED_CSS +

            "})();",

            null);
}
 
源代码18 项目: ProjectX   文件: AMWebViewCompat.java
@Override
public void evaluateJavascript(WebView webView, String script,
                               ValueCallback resultCallback) {
    webView.evaluateJavascript(script, new ValueCallbackKitKat(resultCallback));
}