关于android,webview覆盖shouldInterceptRequest方法,但它使js代码失败

时间:2017-11-20 08:53:54

标签: javascript android webview

谢谢你:

webview加载网址(www.simple.com/step1.html),响应连续

<html>
<body>
    <script>
        location.href = "/step2.html"
    </script>
</body>
</html>

js代码不起作用。在正常情况下,最终页面将是step2。但仍处于第1阶段 当我覆盖shouldInterceptRequest时:

public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
             try {
                URL oUrl = new URL(request.getUrl().toString());

                final HttpURLConnection conn = (HttpURLConnection)oUrl.openConnection();
                CookieManager cookieManager = CookieManager.getInstance();
                String cookie = cookieManager.getCookie(oUrl.getHost());
                if(!TextUtils.isEmpty(cookie))
                    conn.setRequestProperty("Cookie", cookie);
                conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
                conn.setRequestProperty("Accept-Language", Locale.getDefault().toString()+";q=0.8");
                conn.setRequestMethod(request.getMethod());
                conn.setInstanceFollowRedirects(true);
                conn.connect();
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()){
                    @Override
                    public void close() throws IOException {
                        super.close();
                        if (conn != null) {
                            conn.disconnect();
                        }
                    }

                };

                return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), bis);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return super.shouldInterceptRequest(view, request);
        }

1 个答案:

答案 0 :(得分:0)

您是否在WebView中启用了JavaScript?代码是这样的:

myWebView.getSettings().setJavaScriptEnabled(true);