Controlling navigation in the Android WebView class

1k views Asked by At

I an using the WebView class to display tutorial in my apk. I like it as I can manage and update tutorial without making any changes in apk. I keep all tutorial html files in the specific folder on our website.

My question is there any events that will allow me to catch start navigation (when a user clicked on a link). I want to see on what link a user click in my tutorial and as long as a user navigate within the tutorial folder on our website he supposed to be navigating in WebView of my apk. However if there any link which lead outside of the tutorial folder then navigation to this link should be blocked and navigation should be passed to a browser.

I am not sure whether I explained it clearly. I am quite new to Android development. Please see below an example of my code in C# for Windows phone, I need to have the same in Android apk

    /// <summary>
    /// navigation in the application's browser goes as long as it is in the "stockscreenerapp" folder
    /// if user goes out of this folder ("stockscreenerapp" cannot be found in the URL string) then
    /// external default browser is called for further navigation
    /// </summary>
    private async void webBrowser1_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)        {
        if (null != args.Uri) {
            string url = args.Uri.ToString();
            int i = url.IndexOf("stockscreenerapp"); /* check whether "stockscreenerapp" is in the URL address */
            if (i == -1) { args.Cancel = true; await Windows.System.Launcher.LaunchUriAsync(args.Uri); /*if it is not we call external browser and pass URL to it*/}
            else { imgLoading.Visibility = Visibility.Visible; /* show loading image while page is loading */  }
            }
    }
1

There are 1 answers

0
Nathan Vance On

Try using a WebViewClient and listening for onPageStarted. That way you can get the url of the clicked link, check if it's outside of your tutorial, and tell the WebView to stopLoading if it is.

In code, it might look something like this (warning, untested):

WebView webView = new WebView(context);
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted (WebView view, String url, Bitmap favicon) {
       if(Tutorial.doesNotContain(url))
           view.stopLoading();
           view.goBack();
    }
});