injectScriptIntoHtml function
把一段我们自己的脚本挂到文档末尾(</body> 之前,没有就追加)。
为什么挂末端而不是 loadHtmlString 之后 runJavaScript:移动端 WebView 上没有
可靠的「加载完成」回调,早一步执行就落空。随文档一起解析执行,等于把「等页面
就绪」交给浏览器自己排。
⚠️ 调用前必须先用 stripAuthorScripts 摘掉作者的脚本:这个口子只为我们
自己的脚本开(搜索命中定位见 preview_focus.dart、阅读位置见
html_anchor.dart),不能顺带把文档里的任意脚本跑起来。
Implementation
String injectScriptIntoHtml(String html, String script) {
final String tag = '<script>$script</script>';
final RegExpMatch? body = RegExp(
r'</body\s*>',
caseSensitive: false,
).firstMatch(html);
if (body != null) {
return html.replaceRange(body.start, body.start, tag);
}
return '$html$tag';
}