下面列出了android.webkit.WebResourceRequest#isForMainFrame ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (request.isForMainFrame()) {
mIsError = true;
}
if (mClient == null) {
return;
}
mClient.onReceivedError(view, request, error);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request == null || view == null) {
return false;
}
String url = request.getUrl().toString();
boolean isMainFrame = request.isForMainFrame();
boolean isRedirect = SDK_INT >= N && request.isRedirect();
return shouldOverrideUrlLoading(view, url, isMainFrame, isRedirect);
}
/**
* 同名 API 兼容
*/
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.isForMainFrame()) {
onReceivedError(view,
error.getErrorCode(), error.getDescription().toString(),
request.getUrl().toString());
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request == null || view == null) {
return false;
}
String url = request.getUrl().toString();
boolean isMainFrame = request.isForMainFrame();
boolean isRedirect = SDK_INT >= N && request.isRedirect();
return shouldOverrideUrlLoading(view, url, isMainFrame, isRedirect);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request == null || view == null) {
return false;
}
String url = request.getUrl().toString();
// Disabling the URL schemes that cause problems
String[] blacklistedUrls = { "intent:#Intent;action=com.ledger.android.u2f.bridge.AUTHENTICATE" };
for(int i=0; i< blacklistedUrls.length; i++){
String badUrl = blacklistedUrls[i];
if(url.contains(badUrl)){
return true;
}
}
// This works only for API 24+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (request.isForMainFrame() && request.isRedirect()) {
view.loadUrl(url);
return true;
}
}
return super.shouldOverrideUrlLoading(view, request);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request, Boolean onlyMainFrame, Web3Webview webView) {
Uri url = request.getUrl();
String urlStr = url.toString();
if (onlyMainFrame && !request.isForMainFrame()) {
return null;
}
if (Web3WebviewManager.urlStringLooksInvalid(urlStr)) {
return null;
}
try {
String ua = mWebviewSettings.getUserAgentString();
Request req = new Request.Builder()
.header("User-Agent", ua)
.url(urlStr)
.build();
Response response = httpClient.newCall(req).execute();
if (!Web3WebviewManager.responseRequiresJSInjection(response)) {
return null;
}
InputStream is = response.body().byteStream();
MediaType contentType = response.body().contentType();
Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
if (response.code() < HttpURLConnection.HTTP_MULT_CHOICE || response.code() >= HttpURLConnection.HTTP_BAD_REQUEST) {
is = new InputStreamWithInjectedJS(is, webView.injectedOnStartLoadingJS, charset, webView.getContext());
}
return new WebResourceResponse("text/html", charset.name(), is);
} catch (IOException e) {
return null;
}
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.isForMainFrame()) {
onMainFrameError(view,
error.getErrorCode(), error.getDescription().toString(),
request.getUrl().toString());
}
LogUtils.i(TAG, "onReceivedError:" + error.getDescription() + " code:" + error.getErrorCode());
}
@Override
@SuppressLint("NewApi")
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (!request.isForMainFrame()
&& request.getUrl().getPath() != null
&& request.getUrl().getPath().endsWith("/favicon.ico")) {
try {
return new WebResourceResponse("image/png", null, null);
} catch (Exception e) {
Log.e(LOG_TAG, "shouldInterceptRequest failed", e);
}
}
return null;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
// Only update the user visible URL if:
// 1. The purported site URL has actually been requested
// 2. And it's being loaded for the main frame (and not a fake/hidden/iframe request)
// Note also: shouldInterceptRequest() runs on a background thread, so we can't actually
// query WebView.getURL().
// We update the URL when loading has finished too (redirects can happen after a request has been
// made in which case we don't get shouldInterceptRequest with the final URL), but this
// allows us to update the URL during loading.
if (request.isForMainFrame()) {
// WebView will always add a trailing / to the request URL, but currentPageURL may or may
// not have a trailing URL (usually no trailing / when a link is entered via UrlInputFragment),
// hence we do a somewhat convoluted test:
final String requestURL = request.getUrl().toString();
final String currentURL = currentPageURL;
if (UrlUtils.urlsMatchExceptForTrailingSlash(currentURL, requestURL)) {
view.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onURLChanged(currentURL);
}
}
});
}
if (callback != null) {
callback.onRequest(request.hasGesture());
}
}
return super.shouldInterceptRequest(view, request);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (request.isForMainFrame()) {//是否是为 main frame创建
String mErrorUrl = "file:///android_asset/404_error.html";
view.loadUrl(mErrorUrl);
}
}
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (request.isForMainFrame()) {//是否是为 main frame创建
String mErrorUrl = "file:///android_asset/404_error.html";
view.loadUrl(mErrorUrl);
}
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request == null) {
return null;
}
if (!request.getMethod().equalsIgnoreCase("GET") || !request.isForMainFrame()) {
if (request.getMethod().equalsIgnoreCase("GET")
&& (request.getUrl().toString().contains(".js")
|| request.getUrl().toString().contains("json")
|| request.getUrl().toString().contains("css"))) {
synchronized (lock) {
if (!isInjected) {
injectScriptFile(view);
isInjected = true;
}
}
}
super.shouldInterceptRequest(view, request);
return null;
}
HttpUrl httpUrl = HttpUrl.parse(request.getUrl().toString());
if (httpUrl == null) {
return null;
}
Map<String, String> headers = request.getRequestHeaders();
JsInjectorResponse response;
try {
response = jsInjectorClient.loadUrl(httpUrl.toString(), headers);
} catch (Exception ex) {
return null;
}
if (response == null || response.isRedirect) {
return null;
} else {
ByteArrayInputStream inputStream = new ByteArrayInputStream(response.data.getBytes());
WebResourceResponse webResourceResponse = new WebResourceResponse(
response.mime, response.charset, inputStream);
synchronized (lock) {
isInjected = true;
}
return webResourceResponse;
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request == null) {
return null;
}
if (!request.getMethod().equalsIgnoreCase("GET") || !request.isForMainFrame()) {
if (request.getMethod().equalsIgnoreCase("GET")
&& (request.getUrl().toString().contains(".js")
|| request.getUrl().toString().contains("json")
|| request.getUrl().toString().contains("css"))) {
synchronized (lock) {
if (!isInjected) {
injectScriptFile(view);
isInjected = true;
}
}
}
super.shouldInterceptRequest(view, request);
return null;
}
//check for known extensions
if (handleTrustedExtension(request.getUrl().toString()))
{
return null;
}
HttpUrl httpUrl = HttpUrl.parse(request.getUrl().toString());
if (httpUrl == null) {
return null;
}
Map<String, String> headers = request.getRequestHeaders();
JsInjectorResponse response;
try {
response = jsInjectorClient.loadUrl(httpUrl.toString(), headers);
} catch (Exception ex) {
return null;
}
if (response == null || response.isRedirect) {
return null;
} else if (TextUtils.isEmpty(response.data)){
return null;
} else {
ByteArrayInputStream inputStream = new ByteArrayInputStream(response.data.getBytes());
WebResourceResponse webResourceResponse = new WebResourceResponse(
response.mime, response.charset, inputStream);
synchronized (lock) {
isInjected = true;
}
return webResourceResponse;
}
}
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, final WebResourceRequest request) {
if (!blockingEnabled) {
return super.shouldInterceptRequest(view, request);
}
final Uri resourceUri = request.getUrl();
// shouldInterceptRequest() might be called _before_ onPageStarted or shouldOverrideUrlLoading
// are called (this happens when the webview is first shown). However we are notified of the URL
// via notifyCurrentURL in that case.
final String scheme = resourceUri.getScheme();
if (!request.isForMainFrame() &&
!scheme.equals("http") && !scheme.equals("https")) {
// Block any malformed non-http(s) URIs. WebView will already ignore things like market: URLs,
// but not in all cases (malformed market: URIs, such as market:://... will still end up here).
// (Note: data: URIs are automatically handled by WebView, and won't end up here either.)
// file:// URIs are disabled separately by setting WebSettings.setAllowFileAccess()
return new WebResourceResponse(null, null, null);
}
// WebView always requests a favicon, even though it won't be used anywhere. This check
// isn't able to block all favicons (some of them will be loaded using <link rel="shortcut icon">
// with a custom URL which we can't match or detect), but reduces the amount of unnecessary
// favicon loading that's performed.
final String path = resourceUri.getPath();
if (path != null && path.endsWith("/favicon.ico")) {
return new WebResourceResponse(null, null, null);
}
final UrlMatcher matcher = getMatcher(view.getContext());
// Don't block the main frame from being loaded. This also protects against cases where we
// open a link that redirects to another app (e.g. to the play store).
if ((!request.isForMainFrame()) &&
currentPageURL != null &&
matcher.matches(resourceUri, Uri.parse(currentPageURL))) {
// Bandaid for issue #26: currentPageUrl can still be null, and needs to be investigated further.
if (callback != null) {
callback.countBlockedTracker();
}
return new WebResourceResponse(null, null, null);
}
return super.shouldInterceptRequest(view, request);
}