Intercept and override HTTP requests from WebView
It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest()
.
How to intercept link requests in a webView?
This can be achieved by setting the webviewclient eg.
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http://blablablacatchurl")) {
//we have intercepted the desired url call
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
If you want to see if there is a way to deep link to the facebook app, just package the url in an intent and fire it off and see what responds. If facebook doesn't catch it I don't think you can perform the second part of your request in any other way.
Android WebView URL intercept , i want to load only one website and it's pages , and nothing else
In both cases you have consumed the event. try something like below .
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().equals(host)) {
// Intercept URL Load url here return true if url is consumed
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}
});
Or if you want to block all other links then you can use it like below .
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().equals(yourwebsite)) {
return super.shouldOverrideUrlLoading(view, request);
}
return true;
}
});
Keep that in mind that all other links will not work so this can be a bad impression on your app . So i suggest that you should open other links with a browser intent . Like below.
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().equals(yourwebsite)) {
return super.shouldOverrideUrlLoading(view, request);
}else{
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl()));
startActivity(browserIntent);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
});
NOTE:- This is implementation for shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
which is applicable above API 21 . So you should also override shouldOverrideUrlLoading(WebView view, String url)
for previous version in same way .
Flutter Intercept all requests from WebView
https://pub.dev/packages/flutter_inappwebview
useShouldInterceptFetchRequest function should help!
The best way to intercept a WebView request in Android
There are two issues with you code
- Incorrect extension detection
For example, when the code try to get resource extension for this URL:
https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=12&ct=1442476202&rver=6.4.6456.0&wp=MBI_SSL_SHARED&wreply=https:%2F%2Fmail.live.com%2Fdefault.aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai
It will return aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai
which is wrong. There is special method for getting extension from the URL: getFileExtensionFromUrl()
- According to documentation method
MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)
may returnnull
. In this case your code set wrong mime type for the page.
Here is the method code that take into account both these issues
@Override
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
if (mime == null) {
return super.shouldInterceptRequest(view, url);
} else {
HttpURLConnection conn = (HttpURLConnection) new URL(
url).openConnection();
conn.setRequestProperty("User-Agent", userAgent);
return new WebResourceResponse(mime, "UTF-8",
conn.getInputStream());
}
}
intercept request multiple http requests in android webview
mWebView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
List myArrayList = new ArrayList();
myArrayList.add("jquery.mobile-menu.css");
myArrayList.add("jquery.validate.css");
myArrayList.add("responsive.css");
myArrayList.add("Style.css");
for (Object str : myArrayList) {
if (url.contains((CharSequence) str)) {
try {
return getUtf8EncodedCssWebResourceResponse(getAssets().open(String.valueOf("css/" + str)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
List newArray = new ArrayList();
newArray.add("20px.png");newArray.add("30px.png");newArray.add("30px-01.png");newArray.add("30px-02.png");
newArray.add("30px-03.png");newArray.add("30px-04.png");newArray.add("30px-05.png");newArray.add("30px-06.png");
newArray.add("35px.png");newArray.add("arrow.png");newArray.add("arrow1.png");newArray.add("bank.png");
newArray.add("cam.png");newArray.add("dex.png");newArray.add("footer-kk.png");newArray.add("logo1.png");
newArray.add("load.png");newArray.add("logo2.png");newArray.add("logo2@2x.png");newArray.add("logo3.png");
newArray.add("logo3@2x.png");newArray.add("logo-ico.png");newArray.add("logo-ico@2x.png");newArray.add("msf-ico.png");
newArray.add("option-ico.png");newArray.add("option-ico1.png");newArray.add("profile-nav.png");newArray.add("profile-pic-1.png");
newArray.add("profile-pic-2.png");newArray.add("reg-nav-act.png");newArray.add("reg-nav-bg.png");newArray.add("reg-nav-dot.png");
newArray.add("shadow.png");newArray.add("tick.png");newArray.add("tick1.png");newArray.add("view-pro-line.png");
for (Object image : newArray) {
if (url.contains((CharSequence) image)) {
try {
return getimageWebResource(getAssets().open(String.valueOf("images/" + image)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
List jsArray = new ArrayList();
jsArray.add("jquery.validate.js");
jsArray.add("jquery-1.3.2.jpg");
newArray.add("mc_reg.js");
newArray.add("html5shiv.min.js");
newArray.add("jquery.min.js");
newArray.add("jquery.mobile-menu.js");
newArray.add("jquery.mobile-menu.min.js");
newArray.add("respond.min.js");
for (Object js : jsArray) {
if (url.contains((CharSequence) js)) {
try {
return getJsWebResourceResponse(getAssets().open(String.valueOf("js/" + js)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private WebResourceResponse getUtf8EncodedCssWebResourceResponse(InputStream data) {
return new WebResourceResponse("text/css", "UTF-8", data);
}
private WebResourceResponse getJsWebResourceResponse(InputStream data) {
return new WebResourceResponse("text/javascript", "UTF-8", data);
}
private WebResourceResponse getimageWebResource(InputStream data) {
return new WebResourceResponse("image/png", "UTF-8", data);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/webpages.html");
}
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progressBar).setVisibility(View.GONE);
}
});
Flutter webview intercept and add headers to all requests
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.
If you need to add custom headers for each request, you can use the shouldOverrideUrlLoading
event (you need to enable it using useShouldOverrideUrlLoading: true
option).
Instead, if you need to add cookies to your WebView, you can just use the CookieManager
class (CookieManager.setCookie
method to set a cookie).
Here is an example that set a cookie (named ci_session
) in your WebView and also set a custom header (named My-Custom-Header
) for each request:
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController webView;
CookieManager _cookieManager = CookieManager.instance();
@override
void initState() {
super.initState();
_cookieManager.setCookie(
url: "https://github.com/",
name: "ci_session",
value: "54th5hfdcfg34",
domain: ".github.com",
isSecure: true,
);
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialUrl: "https://github.com/",
initialHeaders: {'My-Custom-Header': 'custom_value=564hgf34'},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
useShouldOverrideUrlLoading: true
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {},
onLoadStop: (InAppWebViewController controller, String url) async {
List<Cookie> cookies = await _cookieManager.getCookies(url: url);
cookies.forEach((cookie) {
print(cookie.name + " " + cookie.value);
});
},
shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
print("URL: ${shouldOverrideUrlLoadingRequest.url}");
if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
controller.loadUrl(url: shouldOverrideUrlLoadingRequest.url, headers: {
'My-Custom-Header': 'custom_value=564hgf34'
});
return ShouldOverrideUrlLoadingAction.CANCEL;
}
return ShouldOverrideUrlLoadingAction.ALLOW;
},
))
])),
),
);
}
}
Related Topics
Android Viewpager - Show Preview of Page on Left and Right
Android Device Configuration for Aosp
Onlistitemclick Is Not Working for Listview
Android, How to Read Qr Code in My Application
How to Close Activity and Go Back to Previous Activity in Android
Android, How to Limit Width of Textview (And Add Three Dots at The End of Text)
Turning on Wifi Using Wifimanager Stops to Work on Android 10
CSS Media Queries on Nexus 7, Display Resolution Not Working in Code
How to Update Google Play Services for Android Studio 2.2 Emulators
What Are Best Practices for Using Aes Encryption in Android
How to Save Image Taken from Camera and Show It to Listview - Crashes with "Illegalstateexception"
How Many Activities Vs Fragments
How to Parse JSON Array Without Any Object in Retrofit
How to Get Rid of Incremental Annotation Processing Requested Warning
How to Declare an Extended Height Toolbar/Action Bar on Android Lollipop