【问题标题】:How to get Url of the WebView using WebResourceRequest in Java?如何在 Java 中使用 WebResourceRequest 获取 WebView 的 Url?
【发布时间】:2017-11-08 18:23:03
【问题描述】:
我有这些代码:
public class MyAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//want url of the webview in here
}
我只想知道,如何获取webView的Url来覆盖Url加载。 shouldOverrideUrlLoading(WebView view, String url) 方法在 API21 中已弃用。
提前致谢!
【问题讨论】:
标签:
java
android
android-studio
webview
【解决方案1】:
boolean shouldOverrideUrlLoading (WebView view, String url) 在 API 24 中已弃用,boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) 在 API 级别 24 中添加
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if(Uri.parse(request.getUrl().toString()).getHost().endsWith("google.com")) {
//The host application wants to leave the current WebView and handle the url itself.
return true;
}
if(Uri.parse(request.getUrl().toString()).getHost().endsWith("yandex.com")) {
//The current WebView handles the url.
return false;
}
if(Uri.parse(request.getUrl().toString()).getScheme().equals("file")) {
//The current WebView handles the url.
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
view.getContext().startActivity(intent);
return true;
}
【解决方案2】:
在\Android\sdk\sources\android-25\android\webkit\WebViewClient.java中,可以看到这段代码。
您的问题的简短回答是:
request.getUrl().toString()
查看GrepCode 上的来源。
【解决方案3】:
private String cUrl = "";
cUrl = webView.getUrl();
然后你可以在任何你想要的地方使用它。