Reputation: 21
How check Url change into WebView
@Deprecated
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
String url = view.getUrl();
return true;
}
This function only work on first time change
Upvotes: 0
Views: 6174
Reputation: 21
Please use for this issue shouldInterceptRequest
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
return super.shouldInterceptRequest(view, url);
}
It can be used for check all url change in webview
Upvotes: 1
Reputation: 1268
Don't know why you add @Deprecated
annotation but as I know the old shouldOverrideUrlLoading
method indeed deprecated in API level 24.
So if your minSdkVersion
is 24 or above you can only use public boolean shouldOverrideUrlLoading(WebView, WebResourceRequest)
, but using shouldOverrideUrlLoading()
(like your code did) can just grab the previous URL if URL changed. if you want to grab the current URL after URL changed you can use @JavascriptInterface
First you should create a custom WebViewClient
public class MyWebViewClient extends WebViewClient {
// inject javascript method 'onUrlChange'
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.android.onUrlChange(window.location.href);");
};
// if your minSdkVersion is 24 you can only use this
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
String url = view.getUrl();
// Log.d("LOG","previous_url: " + url);
return false;
}
static class MyJavaScriptInterface {
@JavascriptInterface
public void onUrlChange(String url) {
// Log.d("LOG", "current_url: " + url);
}
}
}
I put both methods into it in case you want, and you can uncomment the Log.d(...)
line to check the URL
In your MainActivity.java
...
WebView mWebView = (WebView) findViewById(R.id.YOUR_VIEW_ID);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.addJavascriptInterface(new MyWebViewClient.MyJavaScriptInterface(),
"android");
mWebView.loadUrl(YOUR_TARGET_URL);
...
Don't forget putting <uses-permission android:name="android.permission.INTERNET" />
into AndroidManifest.xml
Upvotes: 1