Dead loop in android webview backkey for redirect href link

后端 未结 4 2271
挽巷
挽巷 2021-02-14 10:30

I got to a dead loop in Android webview application with backkey while dealing with redirect links.

For example, when my webview started, it goes to link0.

In l

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-14 11:18

    Annoying redirects get into the backforward history. Detect when url loading is triggered by the user, and add those to the backstack instead.

    private List previous = new ArrayList();
    private String mLastUrl;
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.i("DebugDebug", "OnPageFinished " + url);
            mLastUrl = url;
            super.onPageFinished(view, url);
        }
    });
    
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            WebView.HitTestResult hr  = ((WebView)view).getHitTestResult();
            if (hr != null && mLastUrl != null) {
                if (previous.isEmpty() || !previous.get(previous.size() - 1).equals(mLastUrl)) {
                    previous.add(mLastUrl);
                }
                Log.i("DebugDebug", "getExtra = " + hr.getExtra() + "\t\t Type = " + hr.getType());
            }
            return false;
        }
    });
    
    
    @Override
    public void onBackPressed() {
        Log.i("DebugDebug", "onBackPressed");
        int size = previous.size();
        if (size > 0){
            webview.loadUrl(previous.get(size - 1));
            previous.remove(size - 1);
        } else {
            super.onBackPressed();
        }
    }
    

提交回复
热议问题