ChatGPT解决这个技术问题 Extra ChatGPT

Android webview launches browser when calling loadurl

I created an Activity that has a title and a web view in a LinearLayout. In the onResume() method it calls webView.loadUrl(url). The problem is that the activity first shows the title with the rest of the screen blank, then the device browser is launched with the page for the URL. What I want to see is the page being shown in the WebView below the title. What could be the problem?

Edit: Ok, did some further search and found this one:

Clicking URLs opens default browser

It points to the WebView tutorial here.

Just implement the web client and set it.

I mention this because you solved my problem... Thank you.
@Ray, consider writing an answer to this question, if you has found a solution, and accept it. This will help other people with same problem.
I had an even nastier problem. It turns out, even a redirect will load with the browser if a custom WebViewClient is not used.
Must read this - WebView launches browser
This one also tells about it... youtube.com/watch?v=4bIF5In1c8s

J
Jagat Dave

Answering my question based on the suggestions from Maudicus and Hit.

Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:

myWebView.setWebViewClient(new WebViewClient());

For more advanced processing for the web content, consider the ChromeClient.


To avoid WebView to launch the default browser when open initial page.
Thanks for this unbelievable awesome little piece of witchcraft! +1 ...MINUS ONE FOR YOU, Android...
Excellent answer. Solved my problem too.
Does this only work for the initial loading? What if you want to navigate the browser from within the app?
myWebView.webViewClient = WebViewClient() in Kotlin!
J
Jonas Czech

Use this:

lWebView.setWebViewClient(new WebViewClient());

@DigvijaySingh check the original of accepted answer. Originally it didn't have this code. It was added way after this answer
E
Eduard Luca

use like this:

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

    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.loadUrl("https://google.com");
}

A
Abduhafiz

Make your Activity like this.

public class MainActivity extends Activity {
WebView browser;

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

    // find the WebView by name in the main.xml of step 2
    browser=(WebView)findViewById(R.id.wvwMain);

    // Enable javascript
    browser.getSettings().setJavaScriptEnabled(true);  

    // Set WebView client
    browser.setWebChromeClient(new WebChromeClient());

    browser.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                }
        });
     // Load the webpage
    browser.loadUrl("http://google.com/");
   }
}

setJavaScriptEnabled(true) introduces XSS vulnerabilities into your app. Do not use it if you do not need JavaScript
The line enabling JavaScript is super important otherwise you'll get You need to enable JavaScript to run this app. and googling it will only reveal people having issues with react native and you'll go crazy because JavaScript is already enabled in the browser settings.
Wini, you can do smth. like this @ Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mWebView.canGoBack()) { mWebView.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); }
A
Arsh Kaushal

I was facing the same problem and I found the solution Android's official Documentation about WebView

Here is my onCreateView() method and here i used two methods to open the urls

Method 1 is opening url in Browser and

Method 2 is opening url in your desired WebView.
And I am using Method 2 for my Application and this is my code:

public class MainActivity extends Activity {
   private WebView myWebView;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);

      // Show the dummy content as text in a TextView.
      if (mItem != null) {

         /* Method : 1
          This following line is working fine BUT when we click the menu item then it opens the URL in BROWSER not in WebView */
         //((WebView)   rootView.findViewById(R.id.detail_area)).loadUrl(mItem.url);

        // Method : 2
        myWebView = (WebView) rootView.findViewById(R.id.detail_area); // get your WebView form your xml file
        myWebView.setWebViewClient(new WebViewClient()); // set the WebViewClient
        myWebView.loadUrl(mItem.url); // Load your desired url
    }

    return rootView;
}                                                                                               }

c
ceph3us

Try this code...

private void startWebView(String url) {

    //Create new webview Client to show progress dialog
    //When opening a url or click on link

    webView.setWebViewClient(new WebViewClient() {      
        ProgressDialog progressDialog;

        //If you will not use this method url links are opeen in new brower not in webview
        public boolean shouldOverrideUrlLoading(WebView view, String url) {              
            view.loadUrl(url);
            return true;
        }

        //Show loader on url load
        public void onLoadResource (final WebView view, String url) {
            if (progressDialog == null) {
                // in standard case YourActivity.this
                progressDialog = new ProgressDialog(view.getContext());
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
        }
        public void onPageFinished(WebView view, String url) {
            try{
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    }); 

     // Javascript inabled on webview  
    webView.getSettings().setJavaScriptEnabled(true); 

    // Other webview options
    /*
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    */

    /*
     String summary = "<html><body>You scored <b>192</b> points.</body></html>";
     webview.loadData(summary, "text/html", null); 
     */

    //Load url in webview
    webView.loadUrl(url);
}

C
CoolMind

If you see an empty page, enable JavaScript.

webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);

佚名

Simply Answer you can use like this

public class MainActivity extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         WebView webView = new WebView(this);
         setContentView(webView);
         webView.setWebViewClient(new WebViewClient());
         webView.loadUrl("http://www.google.com");
   }
}

V
Vishal Naikawadi

If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.

        webview.webViewClient = WebViewClient()
        webview.webChromeClient = Callback()

private inner class Callback : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
           
            if (newProgress == 0) {
                progressBar.visibility = View.VISIBLE
            } else if (newProgress == 100) {
                progressBar.visibility = View.GONE
            }
        }

    }


Damn, it didn't even occur to me to use both. I use onPageFinished() from WebViewClient and onConsoleMessage() from WebChromeClient. Thanks!
F
Florian T

I just found out that it depends on the formatting of the URL:

https://example.com/example gets opened in the browser

https://example.com/example/ (with / at the end) gets opened in the webView

My code just uses

webview.loadUrl(url)

no need to set

webView.setWebViewClient(new WebViewClient())

at least in my case. Maybe that's useful for some of you.


Its still opens in browser with end / not correct answer..
Actually, I'm finding this same behavior. Not sure how to explain it, but this is what I'm seeing as well.