Reputation: 11786
My web view loads a url that - after completing loading - gets changed to another url.
how can I catch the new url. getURL()
always returns the 1st url not the second.
I can see the new URL if i use a browser but I can't get if from the webview.
Upvotes: 35
Views: 46758
Reputation: 1
You must get the onPageFinished
method with javascript interface
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:window.Android.onUrlChange(window.location.href);");
super.onPageFinished(view, url);
}
});
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void onUrlChange(String url) {
Toast.makeText(getApplicationContext(), url, Toast.LENGTH_SHORT).show();
}
}
Upvotes: 0
Reputation: 3439
In my case WebViewClient wasn't showing if there was changes on the webview, I supposed that is something about the web that is been running.
I could get that information from the WebChromeClient with OnProgressChanged, I don't know if this would help people anyway, but here is the code:
webview.webChromeClient = object : WebChromeClient(){
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 100) {
Log.d("testing", webview.getOriginalUrl())
Log.d("testing", webview.url)
}
}
}
This way I could know what is been loaded and when is finished.
Upvotes: 0
Reputation: 1491
You could use a webClient and implement shouldOverrideUrlLoading to intercept all the urls before the WebView loads them.
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Here put your code
Log.d("My Webview", url);
// return true; //Indicates WebView to NOT load the url;
return false; //Allow WebView to load url
}
});
Upvotes: 57
Reputation: 10573
Use
getOriginalUrl ()
It returns the URL that was originally requested for the current page
getUrl ()
is not always the same as the URL passed to WebViewClient.onPageStarted
because although the load for that URL has begun, the current page may not have changed.
getOriginalUrl ()
gets the original URL for the current page. This is not always the same as the URL passed to WebViewClient.onPageStarted
because although the load for that URL has begun, the current page may not have changed. Also, there may have been redirects resulting in a different URL to that originally requested.
Upvotes: 5