f.dehghanpour
f.dehghanpour

Reputation: 1

Don't navigate to other pages in WebView,disable links and references and go back to first page

I have a webView in Android and I open a html webpage in it. But it's full of links and images: when I click one of them it loads in my webview.
I want to disable this behaviour, so if I click on a link, don't load it and go back to the first page.

I've tried this solution and edited a bit for myself, but it does not work:

webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));

This opens a white page but I want to open the main URL. My webviewclient code:

public class MainActivity extends Activity {

public static String URL = "http://www.example.com/";
private WebView webView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.webView = (WebView) findViewById(R.id.webview);
    MyWebViewClient myWebViewClient = new MyWebViewClient();
    WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));
      webView.reload();
      webView.loadUrl(URL);

    webSettings.setDisplayZoomControls(true);
    webView.setWebViewClient(new WebViewClient());
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack()){
                    webView.goBack();
                    return true;
                }
                break;
        }

    }
    return super.onKeyDown(keyCode, event);
}

public void onBackPressed(){
    if (webView.canGoBack()){
        webView.goBack();
    }
    else{
        super.onBackPressed();
    }
}
}

Upvotes: 0

Views: 904

Answers (2)

user10164217
user10164217

Reputation: 64

You need a WebViewClient that overrides loading url:

webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // url is the url to be loaded
return true; // override url (don't load it)
return false; // let url load
}
});

You can always return true to stay on the same page.

To open Main Url and stay on it, use this: webview.loadUrl(MainUrl);

and then override loading url and always return true:

webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});

Upvotes: 0

Rishav Singla
Rishav Singla

Reputation: 483

you need to overwrite onPageStarted in WebViewClient:

  @Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {

 //here check url i.e equals to your that html page
  // if url equals not load url

and for go to back page check:

if(view.canGoBack())
  // load first page url
}

Upvotes: 1

Related Questions