webview shouldinterceptrequest示例

时间:2011-11-25 20:36:27

标签: android webview

我需要知道shouldinterceptrequest是如何工作的。我不知道如何创建和处理此方法来读取和替换CSS链接。谢谢!

2 个答案:

答案 0 :(得分:63)

嗯,简短的回答是它与shouldOverrideUrlLoading(WebView view, String url)非常相似,如WebView tutorial所示。

为了帮助您入门,请参阅下面的代码。您只需覆盖WebViewClient的shouldInterceptRequest(WebView view, String url)方法即可。显然你不必那样内联,但为了紧凑而我就是这样做的:

    WebView webview = (WebView) findViewById(R.id.webview);
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
            if (url.contains(".css")) {
                return getCssWebResourceResponseFromAsset();
            } else {
                return super.shouldInterceptRequest(view, url);
            }
        }

        /**
         * Return WebResourceResponse with CSS markup from a String. 
         */
        @SuppressWarnings("deprecation")
        private WebResourceResponse getCssWebResourceResponseFromString() {
            return getUtf8EncodedCssWebResourceResponse(new ByteArrayInputStream("body { background-color: #F781F3; }".getBytes()));
        }

        /**
         * Return WebResourceResponse with CSS markup from an asset (e.g. "assets/style.css"). 
         */
        private WebResourceResponse getCssWebResourceResponseFromAsset() {
            try {
                return getUtf8EncodedCssWebResourceResponse(getAssets().open("style.css"));
            } catch (IOException e) {
                return null;
            }
        }

        /**
         * Return WebResourceResponse with CSS markup from a raw resource (e.g. "raw/style.css"). 
         */
        private WebResourceResponse getCssWebResourceResponseFromRawResource() {
            return getUtf8EncodedCssWebResourceResponse(getResources().openRawResource(R.raw.style));
        }

        private WebResourceResponse getUtf8EncodedCssWebResourceResponse(InputStream data) {
            return new WebResourceResponse("text/css", "UTF-8", data);
        }

    });

    webview.loadUrl("http://stackoverflow.com");

抓住加载css文件并返回包含您要加载的数据的WebResourceResponse

请注意,此方法需要 API级别11

如果你想为Android 2.x做类似的事情,你可能想尝试使用前面提到的shouldOverrideUrlLoading(WebView view, String url)来避免加载页面,手动获取它,用你自己的css文件替换引用,最后在WebView上调用loadData(String data, String mimeType, String encoding)(或loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)),将操作的html内容作为字符串传递。

在:

Before

后:

After

答案 1 :(得分:1)

这对你来说也许有趣。它从特定文件夹中读取文件,如果使用此文件名传入请求,则使用资产文件夹中的文件而不是来自Web的文件。

    //get list of files of specific asset folder
    private ArrayList listAssetFiles(String path) {

        List myArrayList = new ArrayList();
        String [] list;
        try {
            list = getAssets().list(path);
            for(String f1 : list){
                myArrayList.add(f1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (ArrayList) myArrayList;
    }

    //get mime type by url
    public String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            if (extension.equals("js")) {
                return "text/javascript";
            }
            else if (extension.equals("woff")) {
                return "application/font-woff";
            }
            else if (extension.equals("woff2")) {
                return "application/font-woff2";
            }
            else if (extension.equals("ttf")) {
                return "application/x-font-ttf";
            }
            else if (extension.equals("eot")) {
                return "application/vnd.ms-fontobject";
            }
            else if (extension.equals("svg")) {
                return "image/svg+xml";
            }
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

    //return webresourceresponse
    public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
        List myArrayList = listAssetFiles(folder);
        for (Object str : myArrayList) {
            if (url.contains((CharSequence) str)) {
                try {
                    Log.i(TAG2, "File:" + str);
                    Log.i(TAG2, "MIME:" + getMimeType(url));
                    return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("NewApi")
    @Override
    public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
        //Log.i(TAG2, "SHOULD OVERRIDE INIT");
        //String url = webResourceRequest.getUrl().toString();
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        //I have some folders for files with the same extension
        if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
            return loadFilesFromAssetFolder(extension, url);
        }
        //more possible extensions for font folder
        if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
            return loadFilesFromAssetFolder("font", url);
        }

        return null;
    }