I am load website with Flutter webview. But I want replace HTML element when it load. For example:
<span class="name">Replace text</span>
How to do?
I am load website with Flutter webview. But I want replace HTML element when it load. For example:
<span class="name">Replace text</span>
How to do?
Share Improve this question asked Sep 21, 2020 at 22:25 FlutterFirebaseFlutterFirebase 2,3537 gold badges34 silver badges68 bronze badges 2-
Hi, you could attach a handler to the load event
document.addEventListener("DOMContentLoaded", function() { // do my replacement });
– IronMan Commented Sep 21, 2020 at 22:29 - @IronMan How to do with Flutter webview? – FlutterFirebase Commented Sep 21, 2020 at 23:07
2 Answers
Reset to default 6So, it depends what library you are using to load your webview.
I have had some good success using webview_flutter_plus
(https://pub.dev/packages/webview_flutter_plus).
With this, you just need to wait for your html to load and inject some javascript to modify whatever html you want.
Like this:
Widget build(BuildContext context) {
return WebViewPlus(
initialUrl: myUrl,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewPlusController webViewController) {
_webViewController = webViewController;
},
onPageFinished: (String url) {
_webViewController.evaluateJavascript('document.querySelector(".name").innerHTML = "new text";');
}
}
}
try this code in the init state :
@override
void initState() {
super.initState();
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onPageFinished: (String url) async {
// Wait for the page and execute JavaScript to manipulate the DOM
await controller.runJavaScript(
"""
(function() {
// Ensure DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
// Find the element
var element = document.querySelector('.name');
if (element) {
// Replace the content
element.textContent = 'Updated text';
}
});
})();
"""
);
},
),
)
..loadRequest(Uri.parse('https://www.website.'));
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745042472a4607894.html
评论列表(0条)