Search in sources :

Example 6 with JsResult

use of android.webkit.JsResult in project WordPress-Android by wordpress-mobile.

the class EditorWebViewAbstract method configureWebView.

@SuppressLint("SetJavaScriptEnabled")
private void configureWebView() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    this.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith("callback") && mJsCallbackReceiver != null) {
                String data = URLDecoder.decode(url);
                String[] split = data.split(":", 2);
                String callbackId = split[0];
                String params = (split.length > 1 ? split[1] : "");
                mJsCallbackReceiver.executeCallback(callbackId, params);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            AppLog.e(T.EDITOR, description);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (!URLUtil.isNetworkUrl(url)) {
                return super.shouldInterceptRequest(view, request);
            }
            // Request and add an authorization header for HTTPS resource requests.
            // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
            // If an auth header is returned, force https:// for the actual HTTP request.
            String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
            if (StringUtils.notNullStr(authHeader).length() > 0) {
                try {
                    url = UrlUtils.makeHttps(url);
                    // Keep any existing request headers from the WebResourceRequest
                    Map<String, String> headerMap = request.getRequestHeaders();
                    for (Map.Entry<String, String> entry : mHeaderMap.entrySet()) {
                        headerMap.put(entry.getKey(), entry.getValue());
                    }
                    headerMap.put("Authorization", authHeader);
                    HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                    return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), conn.getInputStream());
                } catch (IOException e) {
                    AppLog.e(T.EDITOR, e);
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

        /**
             * Compatibility method for API < 21
             */
        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (!URLUtil.isNetworkUrl(url)) {
                return super.shouldInterceptRequest(view, url);
            }
            // Request and add an authorization header for HTTPS resource requests.
            // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
            // If an auth header is returned, force https:// for the actual HTTP request.
            String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
            if (StringUtils.notNullStr(authHeader).length() > 0) {
                try {
                    url = UrlUtils.makeHttps(url);
                    Map<String, String> headerMap = new HashMap<>(mHeaderMap);
                    headerMap.put("Authorization", authHeader);
                    HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                    return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), conn.getInputStream());
                } catch (IOException e) {
                    AppLog.e(T.EDITOR, e);
                }
            }
            return super.shouldInterceptRequest(view, url);
        }
    });
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(@NonNull ConsoleMessage cm) {
            if (cm.messageLevel() == MessageLevel.ERROR) {
                if (mErrorListener != null) {
                    mErrorListener.onJavaScriptError(cm.sourceId(), cm.lineNumber(), cm.message());
                }
                AppLog.e(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            } else {
                AppLog.d(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            }
            return true;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            AppLog.d(T.EDITOR, message);
            if (mErrorListener != null) {
                mErrorListener.onJavaScriptAlert(url, message);
            }
            return true;
        }
    });
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint) ConsoleMessage(android.webkit.ConsoleMessage) JsResult(android.webkit.JsResult) HttpURLConnection(java.net.HttpURLConnection) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) TargetApi(android.annotation.TargetApi) HashMap(java.util.HashMap) Map(java.util.Map) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 7 with JsResult

use of android.webkit.JsResult in project BookReader by JustWayward.

the class ProgressWebView method initWebview.

private void initWebview(String url) {
    mWebView.addJavascriptInterface(this, "android");
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    // 设置可以访问文件
    webSettings.setAllowFileAccess(true);
    // 设置可以支持缩放
    webSettings.setSupportZoom(true);
    // 设置默认缩放方式尺寸是far
    webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    // 设置出现缩放工具
    webSettings.setBuiltInZoomControls(false);
    webSettings.setDefaultFontSize(16);
    mWebView.loadUrl(url);
    // 设置WebViewClient
    mWebView.setWebViewClient(new WebViewClient() {

        // url拦截
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // 使用自己的WebView组件来响应Url加载事件,而不是使用默认浏览器器加载页面
            view.loadUrl(url);
            // 相应完成返回true
            return true;
        // return super.shouldOverrideUrlLoading(view, url);
        }

        // 页面开始加载
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mProgressBar.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        // 页面加载完成
        @Override
        public void onPageFinished(WebView view, String url) {
            mProgressBar.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }

        // WebView加载的所有资源url
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            //				view.loadData(errorHtml, "text/html; charset=UTF-8", null);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });
    // 设置WebChromeClient
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public // 处理javascript中的alert
        boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public // 处理javascript中的confirm
        boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public // 处理javascript中的prompt
        boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        // 设置网页加载的进度条
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);
        }

        // 设置程序的Title
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    });
    mWebView.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                    // 表示按返回键
                    // 后退
                    mWebView.goBack();
                    // 已处理
                    return true;
                }
            }
            return false;
        }
    });
}
Also used : View(android.view.View) WebView(android.webkit.WebView) JsResult(android.webkit.JsResult) KeyEvent(android.view.KeyEvent) Bitmap(android.graphics.Bitmap) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) JsPromptResult(android.webkit.JsPromptResult) WebViewClient(android.webkit.WebViewClient)

Aggregations

JsResult (android.webkit.JsResult)7 WebChromeClient (android.webkit.WebChromeClient)6 WebSettings (android.webkit.WebSettings)6 WebView (android.webkit.WebView)6 WebViewClient (android.webkit.WebViewClient)6 Bitmap (android.graphics.Bitmap)4 View (android.view.View)4 KeyEvent (android.view.KeyEvent)3 JsPromptResult (android.webkit.JsPromptResult)3 SuppressLint (android.annotation.SuppressLint)2 Intent (android.content.Intent)2 WebResourceRequest (android.webkit.WebResourceRequest)2 InjectView (butterknife.InjectView)2 TargetApi (android.annotation.TargetApi)1 Activity (android.app.Activity)1 AlertDialog (android.app.AlertDialog)1 SharedPreferences (android.content.SharedPreferences)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 Handler (android.os.Handler)1