You can use MutationObserver to Observe changes only within the specific container or element where the button is expected to appear. This reduces the number of observed nodes and improves performance
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
InAppWebViewController? _webViewController;
@override
void initState() {
super.initState();
}
@override
void dispose() {
// Clean up resources (e.g., disconnect observers)
if (_webViewController != null) {
_webViewController!.clearCache();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: InAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse('your_web_page_url')),
onWebViewCreated: (controller) {
_webViewController = controller;
},
onPageFinished: (controller, url) async {
await controller.evaluateJavascript(source: """
const targetNode = document.querySelector('#your-target-container'); // Replace with the actual container ID
const config = { childList: true, subtree: true };
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
const button = document.querySelector("a[href^='/GenericUpload/GetFile']");
if (button) {
button.addEventListener('click', () => {
window.flutter_inappwebview.callHandler('MobileAppDownload', button.getAttribute('href'));
});
observer.disconnect(); // Stop observing after the button is found
}
}
});
});
if (targetNode) {
observer.observe(targetNode, config);
}
""");
},
),
);
}
}