I have a requirement where I need to display HTML string in webview_flutter (https://pub.dev/packages/webview_flutter) Plugin. The issue is that the html contains some urls that are not loaded because they require authorization token in header. I am using the method post controller.postRequest(HTMLString,headers: {"authToken": "value"}) but it is not working as in my understanding it is only passing header for the single request. I would really appreciate any help in resolving this.
here is the example html:
<p style=\"margin: 0px\">Hi Team,<br /></p>
<p style=\"margin: 0px\"> <br /></p>
<p style=\"margin: 0px\">Kindly create new Subcategory as TNA360 under
Systems<span class=\"font\" style=\"font-family: Wingdings\">à</span> Business Application.<br /></p>
<p style=\"margin: 0px\">
<img width=\"11.2333in\" height=\"3in\" style=\"width: 11.2333in; height: 3in\" id=\"Picture_x0020_4\" src=\"url of the image\" />
I finally managed to do it using this package https://pub.dev/packages/flutter_inappwebview
here is the full example code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:http/http.dart' as http;
class CustomWebView extends StatefulWidget {
CustomWebView();
@override
_CustomWebViewState createState() => _CustomWebViewState();
}
class _CustomWebViewState extends State<CustomWebView> {
late InAppWebViewController _webViewController;
String htmlContent = ''' your html string with images
''';
@override
Widget build(BuildContext context) {
return InAppWebView(
initialData: InAppWebViewInitialData(data: htmlContent),
onWebViewCreated: (controller) {
_webViewController = controller;
_loadHtmlContent();
},
);
}
Future<void> _loadHtmlContent() async {
final String contentBase64 =
base64Encode(const Utf8Encoder().convert(htmlContent));
final String dataUri = 'data:text/html;base64,$contentBase64';
await _webViewController.loadUrl(urlRequest: URLRequest(url: Uri.parse(dataUri)));
// Fetch the image URLs and pass authentication headers
final RegExp imgRegex = RegExp(r'<img [^>]*src="([^"]+)"');
final Iterable<Match> imgMatches = imgRegex.allMatches(htmlContent);
for (final match in imgMatches) {
final imageUrl = match.group(1);
if (imageUrl != null && imageUrl.startsWith('http')) {
final response = await http.get(Uri.parse(imageUrl), headers: {
'Authorization': 'Bearer token', // Replace with your auth token
});
if (response.statusCode == 200) {
final imageDataBase64 = base64Encode(response.bodyBytes);
final imageDataUri = 'data:image/*;base64,$imageDataBase64';
await _webViewController.evaluateJavascript(
source: 'document.querySelector("img[src=\'$imageUrl\']").src = "$imageDataUri"');
}
}
}
}
}