Search in sources :

Example 21 with WebResourceRequest

use of android.webkit.WebResourceRequest in project IbookerEditorAndroid by zrunker.

the class IbookerEditorPreView method init.

// 初始化
@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
private void init() {
    WebSettings webSettings = this.getSettings();
    // 允许JS
    webSettings.setJavaScriptEnabled(true);
    // 设置允许JS弹窗
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    // access Assets and resources
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCacheEnabled(false);
    // 提高渲染优先级
    webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    // 设置编码格式
    webSettings.setDefaultTextEncodingName("utf-8");
    // 支持自动加载图片
    webSettings.setLoadsImagesAutomatically(true);
    // 关闭webview中缓存
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    // 将图片调整到适合webview的大小
    webSettings.setUseWideViewPort(true);
    // 缩放至屏幕的大小
    webSettings.setLoadWithOverviewMode(true);
    // 支持缩放,默认为true。
    webSettings.setSupportZoom(true);
    // 设置内置的缩放控件。若为false,则该WebView不可缩放
    webSettings.setBuiltInZoomControls(true);
    // 隐藏原生的缩放控件
    webSettings.setDisplayZoomControls(false);
    // 隐藏滚动条
    this.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    // 使页面获取焦点,防止点击无响应
    this.requestFocus();
    // 设置WebViewClient
    this.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            // 当网页加载出错时,加载本地错误文件
            IbookerEditorPreView.this.loadUrl("file:///android_asset/error.html");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            addWebViewListener();
        }
    });
    // 添加js
    ibookerEditorJsCheckImgEvent = new IbookerEditorJsCheckImgEvent();
    this.addJavascriptInterface(ibookerEditorJsCheckImgEvent, "ibookerEditorJsCheckImgEvent");
    // 加载本地HTML
    this.loadUrl("file:///android_asset/ibooker_editor_index.html");
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) WebSettings(android.webkit.WebSettings) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 22 with WebResourceRequest

use of android.webkit.WebResourceRequest in project platform_packages_apps_PdfViewer by CopperheadOS.

the class PdfViewer method onCreate.

@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);
    mWebView = findViewById(R.id.webview);
    final WebSettings settings = mWebView.getSettings();
    settings.setAllowContentAccess(false);
    settings.setAllowFileAccess(false);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setJavaScriptEnabled(true);
    disableSaveFormData(settings);
    CookieManager.getInstance().setAcceptCookie(false);
    mChannel = new Channel();
    mWebView.addJavascriptInterface(mChannel, "channel");
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if ("GET".equals(request.getMethod()) && "https://localhost/placeholder.pdf".equals(request.getUrl().toString())) {
                return new WebResourceResponse("application/pdf", null, mInputStream);
            }
            return null;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mDocumentState = STATE_LOADED;
            invalidateOptionsMenu();
        }
    });
    mTextView = new TextView(this);
    mTextView.setBackgroundColor(Color.DKGRAY);
    mTextView.setTextColor(ColorStateList.valueOf(Color.WHITE));
    mTextView.setTextSize(18);
    mTextView.setPadding(PADDING, 0, PADDING, 0);
    final Intent intent = getIntent();
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (!"application/pdf".equals(intent.getType())) {
            Log.e(TAG, "invalid mime type");
            finish();
            return;
        }
        mUri = intent.getData();
        mPage = 1;
    }
    if (savedInstanceState != null) {
        mUri = savedInstanceState.getParcelable(STATE_URI);
        mPage = savedInstanceState.getInt(STATE_PAGE);
        mZoomLevel = savedInstanceState.getInt(STATE_ZOOM_LEVEL);
        mDocumentProperties = savedInstanceState.getCharSequenceArrayList(STATE_PROPERTIES);
    }
    if (mUri != null) {
        loadPdf();
    }
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) TextView(android.widget.TextView) Intent(android.content.Intent) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 23 with WebResourceRequest

use of android.webkit.WebResourceRequest in project openremote by openremote.

the class MainActivity method initializeWebView.

protected void initializeWebView() {
    LOG.fine("Initializing web view");
    final WebAppInterface webAppInterface = new WebAppInterface(this);
    webView.addJavascriptInterface(webAppInterface, "MobileInterface");
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webView.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    webView.setLongClickable(false);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            // invalid token. The web app will then start a new login.
            if (request.getUrl().getLastPathSegment() != null && request.getUrl().getLastPathSegment().equals("token") && request.getMethod().equals("POST") && errorResponse.getStatusCode() == 400) {
                webAppInterface.tokenService.clearToken();
                return;
            }
            LOG.warning("Error requesting '" + request.getUrl() + "', response code: " + errorResponse.getStatusCode());
            errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (Boolean.parseBoolean(getString(R.string.SSL_IGNORE))) {
                LOG.fine("Ignoring SSL certificate error: " + error.getPrimaryError());
                // Ignore SSL certificate errors
                handler.proceed();
            } else {
                LOG.severe("SSL error: " + error.getPrimaryError());
                LOG.severe("SSL certificate: " + error.getCertificate());
                errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Remote debugging sessions from Chrome trigger "ERR_CACHE_MISS" that don't hurt, but we should not redirect the view
                if (isRemoteDebuggingEnabled() && error.getErrorCode() == ERROR_UNKNOWN) {
                    return;
                }
                // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
                if (request.getUrl().toString().equals("about:blank") && error.getErrorCode() == ERROR_UNSUPPORTED_SCHEME) {
                    return;
                }
                LOG.warning("Error requesting '" + request.getUrl() + "': " + error.getErrorCode());
            }
            errorViewHolder.show(R.string.fatalError, R.string.fatalErrorExplain, false, true);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = "WebApp console (" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + "): " + consoleMessage.message();
            switch(consoleMessage.messageLevel()) {
                case DEBUG:
                case TIP:
                    LOG.fine(msg);
                    break;
                case LOG:
                    LOG.info(msg);
                    break;
                default:
                    LOG.severe(msg);
            }
            return true;
        }
    });
    webView.setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            if (ContextCompat.checkSelfPermission(context, writePermission) != PackageManager.PERMISSION_GRANTED) {
                // Location permission has not been granted yet, request it.
                ActivityCompat.requestPermissions((MainActivity) context, new String[] { writePermission }, WRITE_PERMISSION_REQUEST);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setMimeType(mimetype);
                // ------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                // ------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (dm != null) {
                    Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
                    dm.enqueue(request);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_downloading, Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) WebResourceRequest(android.webkit.WebResourceRequest) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) DownloadManager(android.app.DownloadManager) ConsoleMessage(android.webkit.ConsoleMessage) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 24 with WebResourceRequest

use of android.webkit.WebResourceRequest in project SmartNews by JavenLu.

the class NewsDetailsActivity method initView.

private void initView() {
    WindowUtil.getInstance().setStatusBarTextAndIconDark(NewsDetailsActivity.this);
    initCustomToolBar();
    containerFrameLayout = findViewById(R.id.container);
    fragmentManager = getSupportFragmentManager();
    webView = findViewById(R.id.web_view);
    webView.setWebViewClient(new WebViewClient() {

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

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

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            showErrorFragment();
        }
    });
}
Also used : Bitmap(android.graphics.Bitmap) WebResourceRequest(android.webkit.WebResourceRequest) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 25 with WebResourceRequest

use of android.webkit.WebResourceRequest in project CCIP-Android by CCIP-App.

the class IRCFragment method onCreateView.

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_web, container, false);
    progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    webView = (WebView) view.findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            view.loadUrl(URL_NO_NETWORK);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });
    webView.setWebChromeClient(new WebChromeViewClient(progressBar));
    webView.loadUrl(URL_IRC);
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    if (Build.VERSION.SDK_INT >= 21) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
    }
    return view;
}
Also used : WebChromeViewClient(org.sitcon.ccip.network.webclient.WebChromeViewClient) WebResourceRequest(android.webkit.WebResourceRequest) WebSettings(android.webkit.WebSettings) WebResourceError(android.webkit.WebResourceError) Intent(android.content.Intent) WebView(android.webkit.WebView) View(android.view.View) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) Nullable(android.support.annotation.Nullable)

Aggregations

WebResourceRequest (android.webkit.WebResourceRequest)38 WebView (android.webkit.WebView)37 WebViewClient (android.webkit.WebViewClient)34 Bitmap (android.graphics.Bitmap)22 WebResourceError (android.webkit.WebResourceError)21 WebResourceResponse (android.webkit.WebResourceResponse)16 WebSettings (android.webkit.WebSettings)14 Intent (android.content.Intent)13 View (android.view.View)12 WebChromeClient (android.webkit.WebChromeClient)12 SuppressLint (android.annotation.SuppressLint)11 TextView (android.widget.TextView)9 SslError (android.net.http.SslError)8 SslErrorHandler (android.webkit.SslErrorHandler)8 Uri (android.net.Uri)7 TargetApi (android.annotation.TargetApi)6 IOException (java.io.IOException)5 Nullable (android.support.annotation.Nullable)3 SearchView (android.support.v7.widget.SearchView)3 Toolbar (android.support.v7.widget.Toolbar)3