Search in sources :

Example 1 with JsResult

use of android.webkit.JsResult in project superCleanMaster by joyoyao.

the class DeciveInfoFragment method initWebview.

private void initWebview() {
    // TODO Auto-generated method stub
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    // 设置可以访问文件
    webSettings.setAllowFileAccess(true);
    // 设置可以支持缩放
    webSettings.setSupportZoom(true);
    // 设置默认缩放方式尺寸是far
    webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    // 设置出现缩放工具
    webSettings.setBuiltInZoomControls(false);
    webSettings.setDefaultFontSize(20);
    // 访问assets目录下的文件
    mWebView.loadUrl("http://girl-atlas.com");
    // 设置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) {
            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 View.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 : InjectView(butterknife.InjectView) 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)

Example 2 with JsResult

use of android.webkit.JsResult in project bilibili-android-client by HotBitmapGG.

the class BrowserActivity method setupWebView.

@SuppressLint("SetJavaScriptEnabled")
private void setupWebView() {
    progressBar.spin();
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    webSettings.setDomStorageEnabled(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    mWebView.getSettings().setBlockNetworkImage(true);
    mWebView.setWebViewClient(webViewClient);
    mWebView.requestFocus(View.FOCUS_DOWN);
    mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder b2 = new AlertDialog.Builder(BrowserActivity.this).setTitle(R.string.app_name).setMessage(message).setPositiveButton("确定", (dialog, which) -> result.confirm());
            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }
    });
    mWebView.loadUrl(url);
}
Also used : JsResult(android.webkit.JsResult) ConstantUtil(com.hotbitmapgg.bilibili.utils.ConstantUtil) Bundle(android.os.Bundle) JsResult(android.webkit.JsResult) Uri(android.net.Uri) Intent(android.content.Intent) RxBaseActivity(com.hotbitmapgg.bilibili.base.RxBaseActivity) MenuItem(android.view.MenuItem) BindView(butterknife.BindView) SuppressLint(android.annotation.SuppressLint) R(com.hotbitmapgg.ohmybilibili.R) WebSettings(android.webkit.WebSettings) WebResourceRequest(android.webkit.WebResourceRequest) Handler(android.os.Handler) Menu(android.view.Menu) WebViewClient(android.webkit.WebViewClient) View(android.view.View) WebView(android.webkit.WebView) ActionBar(android.support.v7.app.ActionBar) WebChromeClient(android.webkit.WebChromeClient) TextUtils(android.text.TextUtils) AlertDialog(android.app.AlertDialog) WebResourceError(android.webkit.WebResourceError) CircleProgressView(com.hotbitmapgg.bilibili.widget.CircleProgressView) Toolbar(android.support.v7.widget.Toolbar) Bitmap(android.graphics.Bitmap) ToastUtil(com.hotbitmapgg.bilibili.utils.ToastUtil) ClipboardUtil(com.hotbitmapgg.bilibili.utils.ClipboardUtil) Activity(android.app.Activity) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint)

Example 3 with JsResult

use of android.webkit.JsResult in project cyborg-core by nu-art.

the class CyborgWebView method setupClients.

private void setupClients() {
    setDownloadListener(new DownloadListener() {

        private String downloadingNow;

        @Override
        public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) {
            logInfo("DEBUG-LOG: onDownloadStart... url: " + url + "  userAgent: " + userAgent + "  contentDisposition: " + contentDisposition + "  mimetype: " + mimeType + "  contentLength: " + contentLength);
            if (downloadingNow != null) {
                logWarning("DOWNLOAD IN PROGRESS: " + downloadingNow + "... NOT DOWNLOADING FILE FROM NEW URL: " + url);
                return;
            }
            if (downloadHandler == null) {
                if (getContext() instanceof Application) {
                    logWarning("APPLICATION CONTEXT FOUND!!! NOT DOWNLOADING FILE FROM: " + url);
                    return;
                }
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                getContext().startActivity(i);
                return;
            }
            HandlerThread fileDownloader = new HandlerThread("File Downloader: " + url);
            fileDownloader.start();
            Handler handler = new Handler(fileDownloader.getLooper());
            downloadingNow = url;
            handler.post(new Runnable() {

                @Override
                public void run() {
                    FileOutputStream os = null;
                    InputStream is = null;
                    String fileName = contentDisposition;
                    if (fileName == null)
                        fileName = "unknown-file";
                    int index = fileName.indexOf("filename=\"");
                    if (index != -1)
                        fileName = fileName.substring(index + "filename=\"".length(), fileName.length() - 1);
                    fileName = fileName.replaceAll("[\\*/:<>\\?\\\\\\|\\+,\\.;=\\[\\]\\\"\\'\\^]", "_");
                    try {
                        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                        connection.setRequestProperty("User-Agent", userAgent);
                        connection.setRequestProperty("Content-Type", mimeType);
                        connection.connect();
                        is = connection.getInputStream();
                        File outputFile;
                        int counter = 0;
                        while (true) {
                            outputFile = new File(Storage.getDefaultStorage().getPath() + "/Download", fileName + (counter == 0 ? "" : "(" + counter + ")"));
                            if (!outputFile.exists())
                                break;
                        }
                        final File finalOutputFile = outputFile;
                        FileTools.createNewFile(finalOutputFile);
                        os = new FileOutputStream(finalOutputFile);
                        StreamTools.copy(is, contentLength, os, new ProgressNotifier() {

                            @Override
                            public void reportState(String report) {
                            }

                            @Override
                            public void onCopyStarted() {
                                downloadHandler.onDownloadStarted(url);
                            }

                            @Override
                            public void onProgressPercentage(double percentages) {
                                downloadHandler.onDownloadProgress(url, (float) percentages);
                            }

                            @Override
                            public void onCopyException(Throwable t) {
                                downloadHandler.onDownloadError(url, t);
                            }

                            @Override
                            public void onCopyEnded() {
                                downloadHandler.onDownloadEneded(url, finalOutputFile);
                            }
                        });
                    } catch (Exception e) {
                        downloadHandler.onDownloadError(url, e);
                    } finally {
                        downloadingNow = null;
                        if (os != null)
                            try {
                                os.close();
                            } catch (IOException ignored) {
                            }
                        if (is != null)
                            try {
                                is.close();
                            } catch (IOException ignored) {
                            }
                    }
                }
            });
        }
    });
    setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onProgressChanged... " + newProgress);
            if (pageHandler == null)
                return;
            if (newProgress >= 89)
                onPageFinished(view, view.getUrl());
            pageHandler.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onRequestFocus...");
            if (pageDetailsHandler == null)
                return;
            CyborgWebView.this.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final Callback callback) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onGeolocationPermissionsShowPrompt (origin: " + origin + ", callback: " + callback + ")");
            if (geoLocationHandler == null)
                return;
            geoLocationHandler.onGeolocationPermissionsShowPrompt(origin, new Processor<GeoLocationResponse>() {

                @Override
                public void process(GeoLocationResponse res) {
                    callback.invoke(origin, res.enable, res.remember);
                    settings.setGeolocationEnabled(res.enable);
                }
            });
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (DEBUG)
                logInfo("DEBUG-LOG: onGeolocationPermissionsHidePrompt...");
            if (geoLocationHandler == null)
                return;
            geoLocationHandler.onGeolocationPermissionsShowPrompt();
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg + ", acceptType: " + acceptType + ", capture: " + capture);
            openFileChooser(uploadMsg, acceptType);
        }

        public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg + ", acceptType: " + acceptType);
            if (fileChooserHandler == null)
                uploadMsg.onReceiveValue(null);
            boolean handled = fileChooserHandler.openFileChooser(getUrl(), acceptType, new Processor<Uri>() {

                @Override
                public void process(Uri uri) {
                    uploadMsg.onReceiveValue(uri);
                }
            });
            if (!handled)
                uploadMsg.onReceiveValue(null);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg);
            openFileChooser(uploadMsg, null);
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (DEBUG)
                logInfo("DEBUG-LOG: getDefaultVideoPoster...");
            if (javaScriptHandler == null)
                return null;
            return videoHandler.getDefaultVideoPoster();
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (DEBUG)
                logInfo("DEBUG-LOG: getVideoLoadingProgressView...");
            if (javaScriptHandler == null)
                return null;
            return videoHandler.getVideoLoadingProgressView();
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsAlert (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.confirm();
                return true;
            }
            return javaScriptHandler.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsBeforeUnload (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsBeforeUnload(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsConfirm (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsPrompt (url: " + url + ", message: " + message + ", defaultValue: " + defaultValue + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onCreateWindow (isDialog: " + isDialog + ", isUserGesture: " + isUserGesture + ", resultMsg: " + resultMsg + ")");
            if (windowHandler == null)
                return false;
            return windowHandler.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onCloseWindow...");
            if (windowHandler == null)
                return;
            windowHandler.onCloseWindow(window);
        }

        @Override
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onShowCustomView (callback: " + callback + ")");
            if (javaScriptHandler == null)
                return;
            customViewHandler.onShowCustomView(view, requestedOrientation, callback);
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            onShowCustomView(view, 0, callback);
        }

        @Override
        public void onHideCustomView() {
            if (DEBUG)
                logInfo("DEBUG-LOG: onHideCustomView...");
            if (javaScriptHandler == null)
                return;
            customViewHandler.onHideCustomView();
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedIcon (icon: " + icon + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedIcon(view, icon);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedTitle (title: " + title + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedTouchIconUrl (url: " + url + ", precomposed: " + precomposed + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedTouchIconUrl(view, url, precomposed);
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onRequestFocus...");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onRequestFocus(view);
        }
    });
    setWebViewClient(new WebViewClient() {

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (DEBUG)
                logInfo("DEBUG-LOG: doUpdateVisitedHistory (url: " + url + ", isReload: " + isReload + ")");
            if (pageHandler == null)
                return;
            pageHandler.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onLoadResource (url: " + url + ")");
            if (pageHandler == null)
                return;
            pageHandler.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onPageFinished (url: " + url + ")");
            CyborgWebView.this.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onPageStarted (url: " + url + ", favicon: " + favicon + ")");
            finishedURL = null;
            if (pageHandler == null)
                return;
            pageHandler.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedError (errorCode: " + errorCode + ", description: " + description + ", failingUrl: " + failingUrl + ")");
            if (pageHandler == null)
                return;
            pageHandler.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldOverrideUrlLoading: " + url);
            if (url.toLowerCase().equals("about:blank"))
                return super.shouldOverrideUrlLoading(view, url);
            if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
                if (pageHandler != null && pageHandler.shouldOverrideUrlLoading(view, url))
                    return true;
                return super.shouldOverrideUrlLoading(view, url);
            }
            if (getContext() instanceof Activity && resolveUrl(url))
                return true;
            if (pageHandler != null && pageHandler.resolveNoneHttpUrl(view, url))
                return true;
            if (!(getContext() instanceof Activity))
                return true;
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                getContext().startActivity(intent);
            } catch (Throwable e) {
                logError(e);
            }
            return true;
        }

        /*
			 * requestHandler
			 */
        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onFormResubmission...");
            if (requestHandler == null)
                return;
            requestHandler.onFormResubmission(view, dontResend, resend);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedHttpAuthRequest (host: " + host + ", realm: " + realm + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedHttpAuthRequest(view, handler, host, realm);
        }

        @Override
        @SuppressWarnings("unused")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedLoginRequest (realm: " + realm + ", account: " + account + ", args: " + args + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedLoginRequest(view, realm, account, args);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedSslError (error: " + error + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedSslError(view, handler, error);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldInterceptRequest: " + url);
            if (requestHandler == null)
                return null;
            return requestHandler.shouldInterceptRequest(view, url);
        }

        @Override
        public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onTooManyRedirects...");
            if (requestHandler == null)
                return;
            requestHandler.onTooManyRedirects(view, cancelMsg, continueMsg);
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onUnhandledKeyEvent: " + event);
            if (systemHandler == null)
                return;
            systemHandler.onUnhandledKeyEvent(view, event);
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onScaleChanged: " + oldScale + " => " + newScale);
            if (systemHandler == null)
                return;
            systemHandler.onScaleChanged(view, oldScale, newScale);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldOverrideKeyEvent: " + event);
            if (systemHandler == null)
                return false;
            return systemHandler.shouldOverrideKeyEvent(view, event);
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) Processor(com.nu.art.core.generics.Processor) ProgressNotifier(com.nu.art.core.interfaces.ProgressNotifier) Message(android.os.Message) SslError(android.net.http.SslError) GeoLocationResponse(com.nu.art.cyborg.web.api.WebViewGeoLocationHandler.GeoLocationResponse) Activity(android.app.Activity) Uri(android.net.Uri) URL(java.net.URL) JsResult(android.webkit.JsResult) KeyEvent(android.view.KeyEvent) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) HttpAuthHandler(android.webkit.HttpAuthHandler) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) InputStream(java.io.InputStream) WebViewWindowHandler(com.nu.art.cyborg.web.api.WebViewWindowHandler) SslErrorHandler(android.webkit.SslErrorHandler) Handler(android.os.Handler) HttpAuthHandler(android.webkit.HttpAuthHandler) WebViewFileChooserHandler(com.nu.art.cyborg.web.api.WebViewFileChooserHandler) WebViewJavaScriptHandler(com.nu.art.cyborg.web.api.WebViewJavaScriptHandler) WebViewVideoHandler(com.nu.art.cyborg.web.api.WebViewVideoHandler) WebViewDownloadHandler(com.nu.art.cyborg.web.api.WebViewDownloadHandler) WebViewSystemHandler(com.nu.art.cyborg.web.api.WebViewSystemHandler) WebViewGeoLocationHandler(com.nu.art.cyborg.web.api.WebViewGeoLocationHandler) WebViewPageDetailsHandler(com.nu.art.cyborg.web.api.WebViewPageDetailsHandler) WebViewCustomViewHandler(com.nu.art.cyborg.web.api.WebViewCustomViewHandler) ScriptActionErrorHandler(com.nu.art.cyborg.web.api.ScriptActionErrorHandler) WebViewPageHandler(com.nu.art.cyborg.web.api.WebViewPageHandler) WebViewRequestHandler(com.nu.art.cyborg.web.api.WebViewRequestHandler) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint) IOException(java.io.IOException) ValueCallback(android.webkit.ValueCallback) Callback(android.webkit.GeolocationPermissions.Callback) HandlerThread(android.os.HandlerThread) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) FileOutputStream(java.io.FileOutputStream) QuotaUpdater(android.webkit.WebStorage.QuotaUpdater) Application(android.app.Application) File(java.io.File) JsPromptResult(android.webkit.JsPromptResult)

Example 4 with JsResult

use of android.webkit.JsResult in project Diaspora-Webclient by voidcode.

the class MainActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (isNetworkAvailable()) {
        // load main domain�s rooturl
        SharedPreferences preferences = getSharedPreferences(SETTINGS_FILENAME, MODE_PRIVATE);
        this.main_domain = preferences.getString("currentpod", "");
        // set the home screen
        setContentView(R.layout.main);
        mWeb = (WebView) findViewById(R.id.webView_main);
        // --------------------------------------------------------------------------//
        // start up the webbrowser------------------------------------------------START
        // --------------------------------------------------------------------------//
        WebSettings settings = mWeb.getSettings();
        // set Javascript
        settings.setJavaScriptEnabled(true);
        // settings.setRenderPriority(RenderPriority.HIGH);
        settings.setCacheMode(WebSettings.LOAD_NORMAL);
        // adds JSInterface class to webview
        if (userHasEnableTranslate()) {
            mWeb.addJavascriptInterface(new JSInterface(), "jsinterface");
        }
        // fix to bug 2: cannot reshare
        // see: https://github.com/voidcode/Diaspora-Webclient/issues/2
        mWeb.setWebChromeClient(new WebChromeClient() {

            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
        mWeb.setWebViewClient(new WebViewClient() {

            private String googleapikey;

            private String defaultlanguage;

            private Matcher matcher;

            private Pattern pattern = Pattern.compile("^(https?)://" + main_domain + "[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");

            // load url
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // this see if the user is trying to open a internel or externel link
                if (// if internel(on main_domain) eks: joindiaspora.com
                pattern.matcher(url).matches()) {
                    view.loadUrl(url);
                    return true;
                } else // if user try to open a externel link, then open it in the default webbrowser.
                {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                    return true;
                }
            }

            public void onPageFinished(WebView view, String url) {
                // when finish loading page
                if (mProgress.isShowing()) {
                    mProgress.dismiss();
                } else {
                    if (// adds translate link to all post
                    userHasEnableTranslate()) {
                        SharedPreferences preferences = getSharedPreferences(TRANSLATE_FILENAME, MODE_PRIVATE);
                        this.googleapikey = preferences.getString("googleapikey", "microsoft-translator");
                        // default-language=english
                        this.defaultlanguage = preferences.getString("defaultlanguage", "en");
                        // Inject google translate link via javascript into all posts
                        mWeb.loadUrl("javascript:(function() { " + // get variables			        	    			"var i=0; "+
                        "var ltrs=document.getElementsByClassName('ltr'); " + // loop: adds translate buttons to all 'ltr' tags
                        "for(i=0;i<ltrs.length;i++) " + "{" + // makes new div
                        "var btn = document.createElement('div'); " + // retrive select post
                        "var selectpost = encodeURIComponent(ltrs.item(i).innerHTML); " + // "var selectpost = 'google is a search '; "+
                        "btn.setAttribute('onclick','alert(window.jsinterface.Translate( \"" + main_domain + "\",  \"" + this.googleapikey + "\", \"" + this.defaultlanguage + // adds onclick-handler
                        "\", \"'+selectpost+'\" ));'); " + // adds style
                        "btn.setAttribute('style','margin:15px 0px 15px 0px;'); " + // adds id
                        "btn.id='btn_translate_id_'+i; " + // title on link.
                        "btn.innerHTML='Translate this post'; " + // append new button to post '.ltr'
                        "ltrs.item(i).appendChild(btn); " + "} " + "})()");
                    }
                }
            }
        });
        // then open SettingsActivity
        if (this.main_domain.equals("")) {
            startActivity(new Intent(this, PodSettingsActivity.class));
        } else {
            mProgress = ProgressDialog.show(this, "Stream", "Please wait a moment...");
            // goto start or logon pages
            this.mWeb.loadUrl("https://" + main_domain + "/stream");
            // goto users stream
            Toast.makeText(this, "Pod: " + main_domain, Toast.LENGTH_SHORT).show();
        }
    } else {
        // if user don�t have internet
        this.finish();
        startActivity(new Intent(this, SetupInternetActivity.class));
    }
}
Also used : Pattern(java.util.regex.Pattern) SharedPreferences(android.content.SharedPreferences) Matcher(java.util.regex.Matcher) Intent(android.content.Intent) JsResult(android.webkit.JsResult) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 5 with JsResult

use of android.webkit.JsResult in project WeexErosFramework by bmfe.

the class BMWXWebView method initWebView.

private void initWebView(WebView wv) {
    WebSettings settings = wv.getSettings();
    settings.setAppCacheEnabled(true);
    settings.setUseWideViewPort(true);
    settings.setDomStorageEnabled(true);
    settings.setSupportZoom(false);
    settings.setBuiltInZoomControls(false);
    addWebJavascriptInterface(wv);
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            WXLogUtils.v("tag", "onPageOverride " + url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            WXLogUtils.v("tag", "onPageStarted " + url);
            if (mOnPageListener != null) {
                mOnPageListener.onPageStart(url);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WXLogUtils.v("tag", "onPageFinished " + url);
            if (mOnPageListener != null) {
                mOnPageListener.onPageFinish(url, view.canGoBack(), view.canGoForward());
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (mOnErrorListener != null) {
                // mOnErrorListener.onError("error", "page error code:" + error.getErrorCode() + ", desc:" + error.getDescription() + ", url:" + request.getUrl());
                mOnErrorListener.onError("error", "page error");
            }
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            if (mOnErrorListener != null) {
                mOnErrorListener.onError("error", "http error");
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            if (mOnErrorListener != null) {
                mOnErrorListener.onError("error", "ssl error");
            }
        }
    });
    wv.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            showWebView(newProgress == 100);
            showProgressBar(newProgress != 100);
            WXLogUtils.v("tag", "onPageProgressChanged " + newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mOnPageListener != null) {
                mOnPageListener.onReceivedTitle(view.getTitle());
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            mContentHeight = Integer.parseInt(message);
            mContentHeight = mContentHeight / (WXViewUtils.defaultPixelScaleFactor(getView().getContext()) * 2);
            Map<String, String> params = new HashMap<>();
            params.put("contentHeight", mContentHeight + "");
            if (mWXWeb != null) {
                mWXWeb.fireEvent("bmPageFinish", params);
            }
            result.confirm();
            return true;
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) SuppressLint(android.annotation.SuppressLint) JsResult(android.webkit.JsResult) Bitmap(android.graphics.Bitmap) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) IWebView(com.taobao.weex.ui.view.IWebView) HashMap(java.util.HashMap) Map(java.util.Map) WebViewClient(android.webkit.WebViewClient)

Aggregations

JsResult (android.webkit.JsResult)14 WebChromeClient (android.webkit.WebChromeClient)13 WebView (android.webkit.WebView)13 WebSettings (android.webkit.WebSettings)11 WebViewClient (android.webkit.WebViewClient)9 View (android.view.View)8 Bitmap (android.graphics.Bitmap)7 SuppressLint (android.annotation.SuppressLint)5 KeyEvent (android.view.KeyEvent)5 JsPromptResult (android.webkit.JsPromptResult)5 ConsoleMessage (android.webkit.ConsoleMessage)4 WebResourceRequest (android.webkit.WebResourceRequest)4 WebResourceResponse (android.webkit.WebResourceResponse)4 Activity (android.app.Activity)3 Intent (android.content.Intent)3 Uri (android.net.Uri)3 SslError (android.net.http.SslError)3 SslErrorHandler (android.webkit.SslErrorHandler)3 IWebView (com.taobao.weex.ui.view.IWebView)3 AlertDialog (android.app.AlertDialog)2