Search in sources :

Example 1 with ValueCallback

use of android.webkit.ValueCallback 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 2 with ValueCallback

use of android.webkit.ValueCallback in project vialer-android by VoIPGRID.

the class WebActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);
    // Set the Toolbar to use as ActionBar
    setSupportActionBar((Toolbar) findViewById(R.id.action_bar));
    // Set the Toolbar title
    getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE));
    // Enabled home as up for the Toolbar
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // Enabled home button for the Toolbar
    getSupportActionBar().setHomeButtonEnabled(true);
    // Get the ProgressBar
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    // Get the WebView.
    mWebView = (WebView) findViewById(R.id.web_view);
    // Enable javascript.
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    // Set webview client.
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.INVISIBLE);
            if (getIntent().getStringExtra(PAGE).equals(getString(R.string.web_password_change))) {
                final String js = "javascript:document.getElementById('id_username').value='" + getIntent().getStringExtra(USERNAME) + "';" + "document.getElementById('id_password').value='" + getIntent().getStringExtra(PASSWORD) + "';" + "document.forms[0].submit();";
                if (Build.VERSION.SDK_INT >= 19) {
                    view.evaluateJavascript(js, new ValueCallback<String>() {

                        @Override
                        public void onReceiveValue(String s) {
                        }
                    });
                } else {
                    view.loadUrl(js);
                }
            }
        }
    });
    String uri = getIntent().getStringExtra(PAGE);
    if (uri.startsWith("http")) {
        loadPage(uri);
    } else {
        // request an autologin token and load the requested page.
        autoLoginToken();
    }
    // Track the web view.
    AnalyticsHelper analyticsHelper = new AnalyticsHelper(((AnalyticsApplication) getApplication()).getDefaultTracker());
    analyticsHelper.sendScreenViewTrack(getIntent().getStringExtra(GA_TITLE));
}
Also used : ValueCallback(android.webkit.ValueCallback) Bitmap(android.graphics.Bitmap) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) AnalyticsHelper(com.voipgrid.vialer.analytics.AnalyticsHelper)

Example 3 with ValueCallback

use of android.webkit.ValueCallback in project chromeview by pwnall.

the class AwContentsClientBridge method allowCertificateError.

// If returns false, the request is immediately canceled, and any call to proceedSslError
// has no effect. If returns true, the request should be canceled or proceeded using
// proceedSslError().
// Unlike the webview classic, we do not keep keep a database of certificates that
// are allowed by the user, because this functionality is already handled via
// ssl_policy in native layers.
@CalledByNative
private boolean allowCertificateError(int certError, byte[] derBytes, final String url, final int id) {
    final SslCertificate cert = SslUtil.getCertificateFromDerBytes(derBytes);
    if (cert == null) {
        // if the certificate or the client is null, cancel the request
        return false;
    }
    final SslError sslError = SslUtil.sslErrorFromNetErrorCode(certError, cert, url);
    ValueCallback<Boolean> callback = new ValueCallback<Boolean>() {

        @Override
        public void onReceiveValue(Boolean value) {
            proceedSslError(value.booleanValue(), id);
        }
    };
    mClient.onReceivedSslError(callback, sslError);
    return true;
}
Also used : ValueCallback(android.webkit.ValueCallback) SslCertificate(android.net.http.SslCertificate) SslError(android.net.http.SslError) CalledByNative(org.chromium.base.CalledByNative)

Example 4 with ValueCallback

use of android.webkit.ValueCallback in project SmartMesh_Android by SmartMeshFoundation.

the class AdvancedWebView method init.

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(final Context context) {
    if (context instanceof Activity) {
        mActivity = new WeakReference<Activity>((Activity) context);
    }
    mLanguageIso3 = getLanguageIso3();
    setFocusable(true);
    setFocusableInTouchMode(true);
    setSaveEnabled(true);
    final String filesDir = context.getFilesDir().getPath();
    final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER;
    final WebSettings webSettings = getSettings();
    webSettings.setAllowFileAccess(false);
    setAllowAccessFromFileUrls(webSettings, true);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    if (Build.VERSION.SDK_INT < 18) {
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    webSettings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT < 19) {
        webSettings.setDatabasePath(databaseDir);
    }
    setMixedContentAllowed(webSettings, true);
    setThirdPartyCookiesEnabled(true);
    super.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageStarted(url, favicon);
                }
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageFinished(url);
                }
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageFinished(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            setLastError();
            if (mListener != null) {
                mListener.onPageError(errorCode, description, failingUrl);
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl);
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
            if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("www.")) {
                return super.shouldOverrideUrlLoading(view, url);
            } else {
                return true;
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onLoadResource(view, url);
            } else {
                super.onLoadResource(view, url);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (Build.VERSION.SDK_INT >= 11) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, url);
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            } else {
                return null;
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, request);
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            } else {
                return null;
            }
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onFormResubmission(view, dontResend, resend);
            } else {
                super.onFormResubmission(view, dontResend, resend);
            }
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload);
            } else {
                super.doUpdateVisitedHistory(view, url, isReload);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedSslError(view, handler, error);
            } else {
                super.onReceivedSslError(view, handler, error);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedClientCertRequest(view, request);
                } else {
                    super.onReceivedClientCertRequest(view, request);
                }
            }
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm);
            } else {
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                return mCustomWebViewClient.shouldOverrideKeyEvent(view, event);
            } else {
                return super.shouldOverrideKeyEvent(view, event);
            }
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onUnhandledKeyEvent(view, event);
            } else {
                super.onUnhandledKeyEvent(view, event);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onUnhandledInputEvent(WebView view, InputEvent event) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onUnhandledInputEvent(view, event);
                } else {
                    super.onUnhandledInputEvent(view, event);
                }
            }
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onScaleChanged(view, oldScale, newScale);
            } else {
                super.onScaleChanged(view, oldScale, newScale);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (Build.VERSION.SDK_INT >= 12) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args);
                } else {
                    super.onReceivedLoginRequest(view, realm, account, args);
                }
            }
        }
    });
    super.setWebChromeClient(new WebChromeClient() {

        // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }

        // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, acceptType, null);
        }

        // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileInput(uploadMsg, null);
        }

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            openFileInput(null, filePathCallback);
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onProgressChanged(view, newProgress);
            } else {
                super.onProgressChanged(view, newProgress);
            }
        }

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

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedIcon(view, icon);
            } else {
                super.onReceivedIcon(view, icon);
            }
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
            } else {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onShowCustomView(view, callback);
            } else {
                super.onShowCustomView(view, callback);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (Build.VERSION.SDK_INT >= 14) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback);
                } else {
                    super.onShowCustomView(view, requestedOrientation, callback);
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onHideCustomView();
            } else {
                super.onHideCustomView();
            }
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            } else {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onRequestFocus(view);
            } else {
                super.onRequestFocus(view);
            }
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onCloseWindow(window);
            } else {
                super.onCloseWindow(window);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsAlert(view, url, message, result);
            } else {
                return super.onJsAlert(view, url, message, result);
            }
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsConfirm(view, url, message, result);
            } else {
                return super.onJsConfirm(view, url, message, result);
            }
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result);
            } else {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result);
            } else {
                return super.onJsBeforeUnload(view, url, message, result);
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            if (mGeolocationEnabled) {
                callback.invoke(origin, true, false);
            } else {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                } else {
                    super.onGeolocationPermissionsShowPrompt(origin, callback);
                }
            }
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onGeolocationPermissionsHidePrompt();
            } else {
                super.onGeolocationPermissionsHidePrompt();
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequest(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequest(request);
                } else {
                    super.onPermissionRequest(request);
                }
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequestCanceled(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequestCanceled(request);
                } else {
                    super.onPermissionRequestCanceled(request);
                }
            }
        }

        @Override
        public boolean onJsTimeout() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsTimeout();
            } else {
                return super.onJsTimeout();
            }
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
            } else {
                super.onConsoleMessage(message, lineNumber, sourceID);
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onConsoleMessage(consoleMessage);
            } else {
                return super.onConsoleMessage(consoleMessage);
            }
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getDefaultVideoPoster();
            } else {
                return super.getDefaultVideoPoster();
            }
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getVideoLoadingProgressView();
            } else {
                return super.getVideoLoadingProgressView();
            }
        }

        @Override
        public void getVisitedHistory(ValueCallback<String[]> callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.getVisitedHistory(callback);
            } else {
                super.getVisitedHistory(callback);
            }
        }

        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            } else {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            }
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            } else {
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }
        }
    });
    setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            if (mListener != null) {
                mListener.onDownloadRequested(url, userAgent, contentDisposition, mimetype, contentLength);
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) PermissionRequest(android.webkit.PermissionRequest) ConsoleMessage(android.webkit.ConsoleMessage) Message(android.os.Message) SslError(android.net.http.SslError) ClientCertRequest(android.webkit.ClientCertRequest) FragmentActivity(android.support.v4.app.FragmentActivity) Activity(android.app.Activity) Uri(android.net.Uri) ConsoleMessage(android.webkit.ConsoleMessage) KeyEvent(android.view.KeyEvent) JsResult(android.webkit.JsResult) Bitmap(android.graphics.Bitmap) HttpAuthHandler(android.webkit.HttpAuthHandler) WebChromeClient(android.webkit.WebChromeClient) InputEvent(android.view.InputEvent) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) WebResourceRequest(android.webkit.WebResourceRequest) View(android.view.View) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint) ValueCallback(android.webkit.ValueCallback) Callback(android.webkit.GeolocationPermissions.Callback) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) WebSettings(android.webkit.WebSettings) QuotaUpdater(android.webkit.WebStorage.QuotaUpdater) SuppressLint(android.annotation.SuppressLint) JsPromptResult(android.webkit.JsPromptResult) SuppressLint(android.annotation.SuppressLint)

Example 5 with ValueCallback

use of android.webkit.ValueCallback in project MaterialFBook by ZeeRooo.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Theme.Temas(this, mPreferences);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = findViewById(R.id.webview);
    mNavigationView = findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);
    drawer = findViewById(R.id.drawer_layout);
    // Setup the toolbar
    Toolbar mToolbar = findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    searchToolbar();
    // Setup the DrawLayout
    final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    URLs();
    switch(mPreferences.getString("start_url", "Most_recent")) {
        case "Most_recent":
            mWebView.loadUrl(baseURL + "home.php?sk=h_chr");
            break;
        case "Top_stories":
            mWebView.loadUrl(baseURL + "home.php?sk=h_nor");
            break;
        case "Messages":
            mWebView.loadUrl(baseURL + "messages/");
            break;
        default:
            break;
    }
    DBHelper = new DatabaseHelper(this);
    bookmarks = new ArrayList<>();
    final Cursor data = DBHelper.getListContents();
    while (data.moveToNext()) {
        if (data.getString(1) != null && data.getString(2) != null) {
            bk = new BookmarksH(data.getString(1), data.getString(2));
            bookmarks.add(bk);
        }
    }
    BLAdapter = new BookmarksAdapter(this, bookmarks, DBHelper);
    BookmarksListView = findViewById(R.id.bookmarksListView);
    BookmarksListView.setAdapter(BLAdapter);
    BookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView adapter, View view, int position, long arg) {
            BookmarksH item = (BookmarksH) BookmarksListView.getAdapter().getItem(position);
            mWebView.loadUrl(item.getUrl());
            drawer.closeDrawers();
        }
    });
    ImageButton newbookmark = findViewById(R.id.add_bookmark);
    newbookmark.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            bk = new BookmarksH(mWebView.getTitle(), mWebView.getUrl());
            DBHelper.addData(bk.getTitle(), bk.getUrl(), null);
            bookmarks.add(bk);
            BLAdapter.notifyDataSetChanged();
            CookingAToast.cooking(MainActivity.this, getString(R.string.new_bookmark) + " " + mWebView.getTitle(), Color.WHITE, Color.parseColor("#214594"), R.drawable.ic_bookmarks, false).show();
        }
    });
    mr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_most_recent).getActionView();
    fr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_friendreq).getActionView();
    // Hide buttons if they are disabled
    if (!mPreferences.getBoolean("nav_groups", false))
        mNavigationView.getMenu().findItem(R.id.nav_groups).setVisible(false);
    if (!mPreferences.getBoolean("nav_search", false))
        mNavigationView.getMenu().findItem(R.id.nav_search).setVisible(false);
    if (!mPreferences.getBoolean("nav_mainmenu", false))
        mNavigationView.getMenu().findItem(R.id.nav_mainmenu).setVisible(false);
    if (!mPreferences.getBoolean("nav_most_recent", false))
        mNavigationView.getMenu().findItem(R.id.nav_most_recent).setVisible(false);
    if (!mPreferences.getBoolean("nav_events", false))
        mNavigationView.getMenu().findItem(R.id.nav_events).setVisible(false);
    if (!mPreferences.getBoolean("nav_photos", false))
        mNavigationView.getMenu().findItem(R.id.nav_photos).setVisible(false);
    if (!mPreferences.getBoolean("nav_back", false))
        mNavigationView.getMenu().findItem(R.id.nav_back).setVisible(false);
    if (!mPreferences.getBoolean("nav_exitapp", false))
        mNavigationView.getMenu().findItem(R.id.nav_exitapp).setVisible(false);
    if (!mPreferences.getBoolean("nav_top_stories", false))
        mNavigationView.getMenu().findItem(R.id.nav_top_stories).setVisible(false);
    if (!mPreferences.getBoolean("nav_friendreq", false))
        mNavigationView.getMenu().findItem(R.id.nav_friendreq).setVisible(false);
    // Start the Swipe to reload listener
    swipeView = findViewById(R.id.swipeLayout);
    swipeView.setColorSchemeResources(android.R.color.white);
    swipeView.setProgressBackgroundColorSchemeColor(Theme.getColor(this));
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });
    // Inflate the FAB menu
    mMenuFAB = findViewById(R.id.menuFAB);
    View.OnClickListener mFABClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.textFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_overview\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.photoFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_photo\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer_photo\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.checkinFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_location\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer_checkin\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.topFAB:
                    mWebView.scrollTo(0, 0);
                    break;
                case R.id.shareFAB:
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                    startActivity(Intent.createChooser(shareIntent, getString(R.string.context_share_link)));
                    break;
                default:
                    break;
            }
            mMenuFAB.close(true);
        }
    };
    findViewById(R.id.textFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.photoFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.checkinFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.topFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.shareFAB).setOnClickListener(mFABClickListener);
    mWebView.setOnScrollChangedCallback(new MFBWebView.OnScrollChangedCallback() {

        @Override
        public void onScrollChange(WebView view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            // Make sure the hiding is enabled and the scroll was significant
            if (Math.abs(oldScrollY - scrollY) > getApplication().getResources().getDimensionPixelOffset(R.dimen.fab_scroll_threshold)) {
                if (scrollY > oldScrollY) {
                    // User scrolled down, hide the button
                    mMenuFAB.hideMenuButton(true);
                } else if (scrollY < oldScrollY) {
                    // User scrolled up, show the button
                    mMenuFAB.showMenuButton(true);
                }
            }
        }
    });
    mWebView.getSettings().setGeolocationEnabled(mPreferences.getBoolean("location_enabled", false));
    mWebView.addJavascriptInterface(new JavaScriptInterfaces(this), "android");
    mWebView.addJavascriptInterface(this, "Vid");
    mWebView.getSettings().setBlockNetworkImage(mPreferences.getBoolean("stop_images", false));
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setAllowContentAccess(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    if (Build.VERSION.SDK_INT >= 19)
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    else
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 6.0) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.1.0.4633 Mobile Safari/537.10+");
    mWebView.setWebViewClient(new WebViewClient() {

        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                // clean an url from facebook redirection before processing (no more blank pages on back)
                url = Helpers.cleanAndDecodeUrl(url);
                if (url.contains("mailto:")) {
                    Intent mailto = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(mailto);
                }
                if ((Uri.parse(url).getHost().endsWith("facebook.com") || Uri.parse(url).getHost().endsWith("*.facebook.com") || Uri.parse(url).getHost().endsWith("akamaihd.net") || Uri.parse(url).getHost().endsWith("ad.doubleclick.net") || Uri.parse(url).getHost().endsWith("sync.liverail.com") || Uri.parse(url).getHost().endsWith("cdn.fbsbx.com") || Uri.parse(url).getHost().endsWith("lookaside.fbsbx.com"))) {
                    return false;
                }
                if (url.contains("giphy") || url.contains("gifspace") || url.contains("tumblr") || url.contains("gph.is") || url.contains("gif") || url.contains("fbcdn.net") || url.contains("imgur")) {
                    if (url.contains("giphy") || url.contains("gph")) {
                        if (!url.endsWith(".gif")) {
                            if (url.contains("giphy.com") || url.contains("html5"))
                                url = String.format("http://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
                            else if (url.contains("gph.is") && !url.contains("html5")) {
                                view.loadUrl(url);
                                url = String.format("http://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
                            }
                            if (url.contains("media.giphy.com/media/") && !url.contains("html5")) {
                                String[] giphy = url.split("-");
                                String giphy_id = giphy[giphy.length - 1];
                                url = "http://media.giphy.com/media/" + giphy_id;
                            }
                            if (url.contains("media.giphy.com/media/http://media")) {
                                String[] gph = url.split("/");
                                String gph_id = gph[gph.length - 2];
                                url = "http://media.giphy.com/media/" + gph_id + "/giphy.gif";
                            }
                            if (url.contains("html5/giphy.gif")) {
                                String[] giphy_html5 = url.split("/");
                                String giphy_html5_id = giphy_html5[giphy_html5.length - 3];
                                url = "http://media.giphy.com/media/" + giphy_html5_id + "/giphy.gif";
                            }
                        }
                        if (url.contains("?")) {
                            String[] giphy1 = url.split("\\?");
                            String giphy_html5_id = giphy1[0];
                            url = giphy_html5_id + "/giphy.gif";
                        }
                    }
                    if (url.contains("gifspace")) {
                        if (!url.endsWith(".gif"))
                            url = String.format("http://gifspace.net/image/%s.gif", url.replace("http://gifspace.net/image/", ""));
                    }
                    if (url.contains("phygee")) {
                        if (!url.endsWith(".gif")) {
                            getSrc(url, "span", "img");
                            url = "http://www.phygee.com/" + elements.attr("src");
                        }
                    }
                    if (url.contains("imgur")) {
                        if (!url.endsWith(".gif") && !url.endsWith(".jpg")) {
                            getSrc(url, "div.post-image", "img");
                            url = "https:" + elements.attr("src");
                        }
                    }
                    if (url.contains("media.upgifs.com")) {
                        if (!url.endsWith(".gif")) {
                            getSrc(url, "div.gif-pager-container", "img#main-gif");
                            url = elements.attr("src");
                        }
                    }
                    imageLoader(url, view.getTitle());
                    return true;
                } else {
                    // Open external links in browser
                    Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(browser);
                    return true;
                }
            } catch (NullPointerException npe) {
                return true;
            }
        }

        private void getSrc(final String url, final String select, final String select2) {
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void[] params) {
                    try {
                        Document document = Jsoup.connect(url).get();
                        elements = document.select(select).select(select2);
                    } catch (IOException ioex) {
                        ioex.getStackTrace();
                    }
                    return null;
                }
            }.execute();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            swipeView.setRefreshing(true);
            if (url.contains("https://mbasic.facebook.com/home.php?s="))
                view.loadUrl(baseURL);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            JavaScriptHelpers.videoView(view);
            if (swipeView.isRefreshing())
                JavaScriptHelpers.loadCSS(view, css);
            if (url.contains("facebook.com/composer/mbasic/") || url.contains("https://m.facebook.com/sharer.php?sid="))
                css += "#page{top:0}";
            if (url.contains("/photos/viewer/")) {
                mWebView.loadUrl(baseURL + "photo/view_full_size/?fbid=" + url.substring(url.indexOf("photo=") + 6).split("&")[0]);
                goBack = true;
            }
            if (url.contains("photo.php?fbid=")) {
                mWebView.loadUrl(baseURL + "photo/view_full_size/?fbid=" + url.substring(url.indexOf("fbid=") + 5).split("&")[0]);
                goBack = true;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            swipeView.setRefreshing(false);
            switch(mPreferences.getString("web_themes", "Material")) {
                case "FacebookMobile":
                    break;
                case "Material":
                    css += getString(R.string.Material);
                    break;
                case "MaterialAmoled":
                    css += getString(R.string.MaterialAmoled);
                    css += "::selection {background: #D3D3D3;}";
                    break;
                case "MaterialBlack":
                    css += getString(R.string.MaterialBlack);
                    break;
                case "MaterialPink":
                    css += getString(R.string.MaterialPink);
                    break;
                case "MaterialGrey":
                    css += getString(R.string.MaterialGrey);
                    break;
                case "MaterialGreen":
                    css += getString(R.string.MaterialGreen);
                    break;
                case "MaterialRed":
                    css += getString(R.string.MaterialRed);
                    break;
                case "MaterialLime":
                    css += getString(R.string.MaterialLime);
                    break;
                case "MaterialYellow":
                    css += getString(R.string.MaterialYellow);
                    break;
                case "MaterialPurple":
                    css += getString(R.string.MaterialPurple);
                    break;
                case "MaterialLightBlue":
                    css += getString(R.string.MaterialLightBlue);
                    break;
                case "MaterialOrange":
                    css += getString(R.string.MaterialOrange);
                    break;
                case "MaterialGooglePlayGreen":
                    css += getString(R.string.MaterialGPG);
                    break;
                default:
                    break;
            }
            if (url.contains("lookaside") || url.contains("cdn.fbsbx.com")) {
                Url = url;
                RequestStoragePermission();
            }
            // Enable or disable FAB
            if (url.contains("messages") || !mPreferences.getBoolean("fab_enable", false))
                mMenuFAB.setVisibility(View.GONE);
            else
                mMenuFAB.setVisibility(View.VISIBLE);
            if (url.contains("https://mbasic.facebook.com/composer/?text=")) {
                final UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
                sanitizer.setAllowUnregisteredParamaters(true);
                sanitizer.parseUrl(url);
                final String param = sanitizer.getValue("text");
                view.loadUrl("javascript:(function(){document.querySelector('#composerInput').innerHTML='" + param + "'})()");
            }
            if (url.contains("https://m.facebook.com/public/")) {
                String[] user = url.split("/");
                String profile = user[user.length - 1];
                view.loadUrl("javascript:(function(){document.querySelector('input#u_0_0._5whq.input').value='" + profile + "'})()");
                view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').disabled = false}catch(_){}})()");
                view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').click()}catch(_){}})()");
            }
            // Hide Orange highlight on focus
            css += "*{-webkit-tap-highlight-color:transparent;outline:0}";
            if (mPreferences.getBoolean("hide_menu_bar", true))
                css += "#page{top:-45px}";
            // Hide the status editor on the News Feed if setting is enabled
            if (mPreferences.getBoolean("hide_editor_newsfeed", true))
                css += "#mbasic_inline_feed_composer{display:none}";
            // Hide 'Sponsored' content (ads)
            if (mPreferences.getBoolean("hide_sponsored", true))
                css += "article[data-ft*=ei]{display:none}";
            // Hide birthday content from News Feed
            if (mPreferences.getBoolean("hide_birthdays", true))
                css += "article#u_1j_4{display:none}" + "article._55wm._5e4e._5fjt{display:none}";
            if (mPreferences.getBoolean("comments_recently", true))
                css += "._15ks+._4u3j{display:none}";
            css += "._i81:after {display: none;}";
            if (sharedFromGallery != null)
                view.loadUrl("javascript:(function(){try{document.getElementsByClassName(\"_56bz _54k8 _52jh _5j35 _157e\")[0].click()}catch(_){document.getElementsByClassName(\"_50ux\")[0].click()}})()");
            css += "article#u_0_q._d2r{display:none}";
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            // Double check that we don't have any existing callbacks
            if (sharedFromGallery != null)
                filePathCallback.onReceiveValue(new Uri[] { sharedFromGallery });
            mFilePathCallback = filePathCallback;
            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                // Error occurred while creating the File
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else
                    takePictureIntent = null;
            }
            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");
            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null)
                intentArray = new Intent[] { takePictureIntent };
            else
                intentArray = new Intent[0];
            if (sharedFromGallery == null) {
                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
            }
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // openFileChooser for Android 3.0+
        private void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            // Update message
            if (sharedFromGallery != null)
                uploadMsg.onReceiveValue(sharedFromGallery);
            else
                mUploadMessage = uploadMsg;
            File imageStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!imageStorageDir.exists()) {
                imageStorageDir.mkdirs();
            }
            // Create camera captured image file path and name
            File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
            mCapturedImageURI = Uri.fromFile(file);
            // Camera capture image intent
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            if (sharedFromGallery == null) {
                Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            }
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            final String imageFileName = "JPEG_" + String.valueOf(System.currentTimeMillis()) + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            final File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
            return imageFile;
        }

        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (view.getUrl().contains("home.php?sk=h_nor"))
                setTitle(R.string.menu_top_stories);
            else if (title.contains("Facebook"))
                setTitle(R.string.menu_most_recent);
            else
                setTitle(title);
        }
    });
    // Add OnClick listener to Profile picture
    ImageView profileImage = mNavigationView.getHeaderView(0).findViewById(R.id.profile_picture);
    profileImage.setClickable(true);
    profileImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            drawer.closeDrawers();
            mWebView.loadUrl(baseURL + "me");
        }
    });
    mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    if (getIntent() != null)
        UrlIntent(getIntent());
}
Also used : ValueCallback(android.webkit.ValueCallback) GeolocationPermissions(android.webkit.GeolocationPermissions) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) Cursor(android.database.Cursor) Document(org.jsoup.nodes.Document) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) Uri(android.net.Uri) BookmarksH(me.zeeroooo.materialfb.Misc.BookmarksH) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) ImageButton(android.widget.ImageButton) Bitmap(android.graphics.Bitmap) WebChromeClient(android.webkit.WebChromeClient) JavaScriptInterfaces(me.zeeroooo.materialfb.WebView.JavaScriptInterfaces) ImageView(android.widget.ImageView) WebView(android.webkit.WebView) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) Toolbar(android.support.v7.widget.Toolbar) WebViewClient(android.webkit.WebViewClient) BookmarksAdapter(me.zeeroooo.materialfb.Misc.BookmarksAdapter) WebResourceRequest(android.webkit.WebResourceRequest) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) Parcelable(android.os.Parcelable) IOException(java.io.IOException) NavigationView(android.support.design.widget.NavigationView) SearchView(android.support.v7.widget.SearchView) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) WebView(android.webkit.WebView) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) TextView(android.widget.TextView) ListView(android.widget.ListView) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) DatabaseHelper(me.zeeroooo.materialfb.Misc.DatabaseHelper) SuppressLint(android.annotation.SuppressLint) AdapterView(android.widget.AdapterView) File(java.io.File) UrlQuerySanitizer(android.net.UrlQuerySanitizer)

Aggregations

ValueCallback (android.webkit.ValueCallback)7 WebView (android.webkit.WebView)5 SuppressLint (android.annotation.SuppressLint)4 Bitmap (android.graphics.Bitmap)4 WebViewClient (android.webkit.WebViewClient)4 Activity (android.app.Activity)3 Uri (android.net.Uri)3 SslError (android.net.http.SslError)3 View (android.view.View)3 WebChromeClient (android.webkit.WebChromeClient)3 Intent (android.content.Intent)2 Message (android.os.Message)2 KeyEvent (android.view.KeyEvent)2 DownloadListener (android.webkit.DownloadListener)2 Callback (android.webkit.GeolocationPermissions.Callback)2 HttpAuthHandler (android.webkit.HttpAuthHandler)2 JsPromptResult (android.webkit.JsPromptResult)2 JsResult (android.webkit.JsResult)2 SslErrorHandler (android.webkit.SslErrorHandler)2 WebResourceRequest (android.webkit.WebResourceRequest)2