Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat: add custom JavaScript captcha verification

Predidit9a3e26990091
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 6b7209fd..9ccf1eec 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -72,6 +72,9 @@ class _SourceSheetState extends State<SourceSheet>
/// 根据插件的验证类型分发到对应的验证对话框
void showAntiCrawlerDialog(Plugin plugin) {
switch (plugin.antiCrawlerConfig.captchaType) {
+ case CaptchaType.customJavaScript:
+ showCustomScriptDialog(plugin);
+ break;
case CaptchaType.autoClickButton:
showButtonClickDialog(plugin);
break;
@@ -156,20 +159,60 @@ class _SourceSheetState extends State<SourceSheet>
}
void showButtonClickDialog(Plugin plugin) {
- /// flag whether onVerified was fired by the auto-click flow (cookies already saved + page unloaded)
- bool autoVerified = false;
+ showAutomatedVerifyDialog(
+ plugin,
+ statusText: '${plugin.name} 正在自动完成验证,请稍候',
+ detailText: '已检测到验证按钮并模拟点击,等待验证通过…',
+ startVerification: (provider, searchUrl, onVerified) {
+ return provider.loadForButtonClick(
+ url: searchUrl,
+ buttonXpath: plugin.antiCrawlerConfig.captchaButton,
+ pluginName: plugin.name,
+ onVerified: onVerified,
+ );
+ },
+ );
+ }
+
+ void showCustomScriptDialog(Plugin plugin) {
+ showAutomatedVerifyDialog(
+ plugin,
+ statusText: '${plugin.name} 正在执行验证脚本,请稍候',
+ detailText: '已加载验证页面并执行自定义脚本,等待验证通过…',
+ startVerification: (provider, searchUrl, onVerified) {
+ return provider.loadForCustomScript(
+ url: searchUrl,
+ script: plugin.antiCrawlerConfig.captchaScript,
+ pluginName: plugin.name,
+ onVerified: onVerified,
+ );
+ },
+ );
+ }
+
+ void showAutomatedVerifyDialog(
+ Plugin plugin, {
+ required String statusText,
+ required String detailText,
+ required Future<void> Function(
+ CaptchaProvider provider,
+ String searchUrl,
+ void Function() onVerified,
+ ) startVerification,
+ }) {
+ bool verified = false;
_captchaProvider?.dispose();
_captchaProvider = CaptchaProvider();
+ final provider = _captchaProvider!;
final searchUrl = plugin.searchURL
.replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
void onVerified() {
- if (autoVerified) return;
- autoVerified = true;
+ if (verified) return;
+ verified = true;
KazumiDialog.dismiss();
- // show a 3s countdown progress dialog before re-querying
KazumiDialog.showTimedSuccessDialog(
title: '验证成功',
message: '正在重新检索,请稍候…',
@@ -177,23 +220,15 @@ class _SourceSheetState extends State<SourceSheet>
);
}
- _captchaProvider!.loadForButtonClick(
- url: searchUrl,
- buttonXpath: plugin.antiCrawlerConfig.captchaButton,
- pluginName: plugin.name,
- onVerified: onVerified,
- );
+ unawaited(startVerification(provider, searchUrl, onVerified));
KazumiDialog.show(
onDismiss: () async {
- // Capture the current provider instance locally before any await.
final provider = _captchaProvider;
_captchaProvider = null;
- if (autoVerified) {
- // auto-verify already saved cookies and unloaded the page
+ if (verified) {
provider?.dispose();
} else {
- // save whatever cookies are present and unload the page
await provider?.saveAndUnload(plugin.name);
provider?.dispose();
queryManager?.querySource(keyword, plugin.name);
@@ -215,14 +250,14 @@ class _SourceSheetState extends State<SourceSheet>
),
const SizedBox(height: 4),
Text(
- '${plugin.name} 正在自动完成验证,请稍候',
+ statusText,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 24),
const CircularProgressIndicator(),
const SizedBox(height: 12),
Text(
- '已检测到验证按钮并模拟点击,等待验证通过…',
+ detailText,
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 82b63cfe..90b4655e 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -42,13 +42,25 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
final TextEditingController captchaImageController = TextEditingController();
final TextEditingController captchaInputController = TextEditingController();
final TextEditingController captchaButtonController = TextEditingController();
+ final TextEditingController captchaDetectValueController =
+ TextEditingController();
+ final TextEditingController captchaScriptController = TextEditingController();
bool antiCrawlerEnabled = false;
int captchaType = CaptchaType.imageCaptcha;
+ int captchaDetectType = CaptchaDetectType.xpath;
final MenuController captchaTypeMenuController = MenuController();
+ final MenuController captchaDetectTypeMenuController = MenuController();
static const Map<int, String> _captchaTypeMap = {
CaptchaType.imageCaptcha: '图片验证码',
CaptchaType.autoClickButton: '自动点击按钮',
+ CaptchaType.customJavaScript: '自定义 JS 验证',
+ };
+
+ static const Map<int, String> _captchaDetectTypeMap = {
+ CaptchaDetectType.xpath: 'XPath',
+ CaptchaDetectType.text: '文本',
+ CaptchaDetectType.regex: '正则',
};
@override
@@ -79,6 +91,10 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaImageController.text = plugin.antiCrawlerConfig.captchaImage;
captchaInputController.text = plugin.antiCrawlerConfig.captchaInput;
captchaButtonController.text = plugin.antiCrawlerConfig.captchaButton;
+ captchaDetectType = plugin.antiCrawlerConfig.captchaDetectType;
+ captchaDetectValueController.text =
+ plugin.antiCrawlerConfig.captchaDetectValue;
+ captchaScriptController.text = plugin.antiCrawlerConfig.captchaScript;
}
@override
@@ -99,6 +115,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaImageController.dispose();
captchaInputController.dispose();
captchaButtonController.dispose();
+ captchaDetectValueController.dispose();
+ captchaScriptController.dispose();
super.dispose();
}
@@ -266,9 +284,15 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
title: Text('验证类型',
style: TextStyle(fontFamily: fontFamily)),
description: Text(
- captchaType == CaptchaType.imageCaptcha
- ? '图片验证码(展示验证码图片,用户手动输入)'
- : '自动点击验证按钮(检测到按钮后自动模拟点击)',
+ switch (captchaType) {
+ CaptchaType.imageCaptcha =>
+ '图片验证码(展示验证码图片,用户手动输入)',
+ CaptchaType.autoClickButton =>
+ '自动点击验证按钮(检测到按钮后自动模拟点击)',
+ CaptchaType.customJavaScript =>
+ '自定义 JS 验证(加载页面后执行规则脚本)',
+ _ => '未知验证类型',
+ },
style: TextStyle(fontFamily: fontFamily),
),
value: MenuAnchor(
@@ -307,6 +331,71 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
],
),
),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ if (captchaDetectTypeMenuController.isOpen) {
+ captchaDetectTypeMenuController.close();
+ } else {
+ captchaDetectTypeMenuController.open();
+ }
+ },
+ title: Text('验证页检测方式',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('优先使用该标记判断搜索响应是否为验证页',
+ style: TextStyle(fontFamily: fontFamily)),
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: captchaDetectTypeMenuController,
+ builder: (_, __, ___) => Text(
+ _captchaDetectTypeMap[captchaDetectType] ??
+ '未知',
+ style: TextStyle(fontFamily: fontFamily),
+ ),
+ menuChildren: [
+ for (final entry
+ in _captchaDetectTypeMap.entries)
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => setState(
+ () => captchaDetectType = entry.key),
+ child: Container(
+ height: 48,
+ constraints:
+ const BoxConstraints(minWidth: 160),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ entry.value,
+ style: TextStyle(
+ color:
+ entry.key == captchaDetectType
+ ? Theme.of(context)
+ .colorScheme
+ .primary
+ : null,
+ fontFamily: fontFamily,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaDetectValueController,
+ label: 'CaptchaDetectValue',
+ hint: captchaDetectType == CaptchaDetectType.text
+ ? '身份验证'
+ : captchaDetectType == CaptchaDetectType.regex
+ ? '身份验证|smart_verify'
+ : '//button[@id="verify"]',
+ helper: '留空时回退到旧的图片/按钮 XPath 检测',
+ ),
+ ),
if (captchaType == CaptchaType.imageCaptcha) ...[
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
@@ -329,20 +418,35 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
),
),
],
- CustomSettingsTile(
- child: (info) => _buildTextFieldTile(
- context,
- info,
- controller: captchaButtonController,
- label: captchaType == CaptchaType.imageCaptcha
- ? 'CaptchaButton (XPath)'
- : 'VerifyButton (XPath)',
- hint: '//button[@type="submit"]',
- helper: captchaType == CaptchaType.imageCaptcha
- ? '验证提交按钮元素的 XPath'
- : '验证按钮元素的 XPath,检测到后自动点击',
+ if (captchaType != CaptchaType.customJavaScript)
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaButtonController,
+ label: captchaType == CaptchaType.imageCaptcha
+ ? 'CaptchaButton (XPath)'
+ : 'VerifyButton (XPath)',
+ hint: '//button[@type="submit"]',
+ helper: captchaType == CaptchaType.imageCaptcha
+ ? '验证提交按钮元素的 XPath'
+ : '验证按钮元素的 XPath,检测到后自动点击',
+ ),
+ ),
+ if (captchaType == CaptchaType.customJavaScript)
+ CustomSettingsTile(
+ child: (info) => _buildTextFieldTile(
+ context,
+ info,
+ controller: captchaScriptController,
+ label: 'CaptchaScript (JavaScript)',
+ hint:
+ 'KazumiCaptcha.log("ready"); KazumiCaptcha.done();',
+ helper:
+ '可调用 KazumiCaptcha.log/clicked/done/fail',
+ maxLines: 8,
+ ),
),
- ),
],
],
),
@@ -386,6 +490,9 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaImage: captchaImageController.text,
captchaInput: captchaInputController.text,
captchaButton: captchaButtonController.text,
+ captchaDetectType: captchaDetectType,
+ captchaDetectValue: captchaDetectValueController.text,
+ captchaScript: captchaScriptController.text,
));
Modular.to
.pushNamed('/settings/plugin/test', arguments: pluginText);
@@ -421,6 +528,9 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaImage: captchaImageController.text,
captchaInput: captchaInputController.text,
captchaButton: captchaButtonController.text,
+ captchaDetectType: captchaDetectType,
+ captchaDetectValue: captchaDetectValueController.text,
+ captchaScript: captchaScriptController.text,
);
pluginsController.updatePlugin(plugin);
Navigator.of(context).pop();
@@ -438,6 +548,7 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
required String label,
String? hint,
String? helper,
+ int maxLines = 1,
}) {
return Column(
mainAxisSize: MainAxisSize.min,
@@ -455,6 +566,7 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: TextField(
controller: controller,
+ maxLines: maxLines,
decoration: InputDecoration(
labelText: label,
hintText: hint,
diff --git a/lib/plugins/anti_crawler_config.dart b/lib/plugins/anti_crawler_config.dart
index 461c4f7b..d240b8e1 100644
--- a/lib/plugins/anti_crawler_config.dart
+++ b/lib/plugins/anti_crawler_config.dart
@@ -2,11 +2,20 @@
///
/// - [imageCaptcha] (1): WebView 抓取验证码图片,引导用户手动输入后提交
/// - [autoClickButton] (2): WebView 检测到验证按钮后自动点击,无需用户交互
+/// - [customJavaScript] (3): WebView 执行规则提供的验证脚本
///
-/// 保留整数表示以便将来新增第三种及更多验证方式时向后兼容。
+/// 保留整数表示以便继续新增验证方式时向后兼容。
class CaptchaType {
static const int imageCaptcha = 1;
static const int autoClickButton = 2;
+ static const int customJavaScript = 3;
+}
+
+/// 反反爬虫验证页检测方式
+class CaptchaDetectType {
+ static const int xpath = 1;
+ static const int text = 2;
+ static const int regex = 3;
}
/// 反反爬虫配置
@@ -21,6 +30,7 @@ class AntiCrawlerConfig {
///
/// - [CaptchaType.imageCaptcha] (1):图片验证码,需要用户手动输入
/// - [CaptchaType.autoClickButton] (2):自动点击验证按钮,无需用户交互
+ /// - [CaptchaType.customJavaScript] (3):执行规则提供的验证脚本
int captchaType;
/// 验证码图片元素的 XPath 选择器(仅 captchaType == 1 时使用)
@@ -35,14 +45,29 @@ class AntiCrawlerConfig {
///
/// - captchaType == 1:提交验证码的按钮,模拟点击提交
/// - captchaType == 2:目标验证按钮(如"我不是机器人"),检测到后自动点击
+ /// - captchaType == 3:不使用该字段
String captchaButton;
+ /// 验证页检测方式,见 [CaptchaDetectType] 中的常量
+ int captchaDetectType;
+
+ /// 验证页检测内容
+ ///
+ /// 根据 [captchaDetectType] 可表示 XPath、普通文本或正则表达式。
+ String captchaDetectValue;
+
+ /// 自定义 JS 验证脚本(仅 captchaType == 3 时使用)
+ String captchaScript;
+
AntiCrawlerConfig({
required this.enabled,
required this.captchaType,
required this.captchaImage,
required this.captchaInput,
required this.captchaButton,
+ this.captchaDetectType = CaptchaDetectType.xpath,
+ this.captchaDetectValue = '',
+ this.captchaScript = '',
});
factory AntiCrawlerConfig.fromJson(Map<String, dynamic> json) {
@@ -52,6 +77,9 @@ class AntiCrawlerConfig {
captchaImage: json['captchaImage'] ?? '',
captchaInput: json['captchaInput'] ?? '',
captchaButton: json['captchaButton'] ?? '',
+ captchaDetectType: json['captchaDetectType'] ?? CaptchaDetectType.xpath,
+ captchaDetectValue: json['captchaDetectValue'] ?? '',
+ captchaScript: json['captchaScript'] ?? '',
);
}
@@ -62,6 +90,9 @@ class AntiCrawlerConfig {
captchaImage: '',
captchaInput: '',
captchaButton: '',
+ captchaDetectType: CaptchaDetectType.xpath,
+ captchaDetectValue: '',
+ captchaScript: '',
);
}
@@ -72,6 +103,9 @@ class AntiCrawlerConfig {
'captchaImage': captchaImage,
'captchaInput': captchaInput,
'captchaButton': captchaButton,
+ 'captchaDetectType': captchaDetectType,
+ 'captchaDetectValue': captchaDetectValue,
+ 'captchaScript': captchaScript,
};
}
@@ -81,6 +115,9 @@ class AntiCrawlerConfig {
String? captchaImage,
String? captchaInput,
String? captchaButton,
+ int? captchaDetectType,
+ String? captchaDetectValue,
+ String? captchaScript,
}) {
return AntiCrawlerConfig(
enabled: enabled ?? this.enabled,
@@ -88,6 +125,9 @@ class AntiCrawlerConfig {
captchaImage: captchaImage ?? this.captchaImage,
captchaInput: captchaInput ?? this.captchaInput,
captchaButton: captchaButton ?? this.captchaButton,
+ captchaDetectType: captchaDetectType ?? this.captchaDetectType,
+ captchaDetectValue: captchaDetectValue ?? this.captchaDetectValue,
+ captchaScript: captchaScript ?? this.captchaScript,
);
}
}
diff --git a/lib/plugins/plugins.dart b/lib/plugins/plugins.dart
index 7e73e0ec..2aaea65b 100644
--- a/lib/plugins/plugins.dart
+++ b/lib/plugins/plugins.dart
@@ -2,6 +2,7 @@ import 'package:dio/dio.dart';
import 'package:kazumi/modules/search/plugin_search_module.dart';
import 'package:kazumi/modules/roads/road_module.dart';
import 'package:kazumi/request/clients/plugin_site_client.dart';
+import 'package:html/dom.dart' show Element;
import 'package:html/parser.dart';
import 'package:kazumi/request/config/api_endpoints.dart';
import 'package:kazumi/utils/logger.dart';
@@ -210,21 +211,10 @@ class Plugin {
var htmlElement = parse(htmlString).documentElement!;
- // Detect captcha challenge: if antiCrawlerConfig is enabled, check both
- // captchaImage and captchaButton XPaths — if either matches, throw so
- // callers can show the dedicated captcha UI instead of a generic error.
- if (antiCrawlerConfig.enabled) {
- final List<String> detectionXpaths = [
- antiCrawlerConfig.captchaImage,
- antiCrawlerConfig.captchaButton,
- ].where((x) => x.isNotEmpty).toList();
- final bool captchaDetected = detectionXpaths
- .any((xpath) => htmlElement.queryXPath(xpath).node != null);
- if (captchaDetected) {
- KazumiLogger()
- .w('Plugin: $name detected captcha challenge in search response');
- throw CaptchaRequiredException(name);
- }
+ if (detectsCaptchaChallenge(htmlString, htmlElement: htmlElement)) {
+ KazumiLogger()
+ .w('Plugin: $name detected captcha challenge in search response');
+ throw CaptchaRequiredException(name);
}
htmlElement.queryXPath(searchList).nodes.forEach((element) {
@@ -356,6 +346,39 @@ class Plugin {
}
}
+ bool detectsCaptchaChallenge(String htmlString, {Element? htmlElement}) {
+ if (!antiCrawlerConfig.enabled) return false;
+
+ final detectValue = antiCrawlerConfig.captchaDetectValue.trim();
+ if (detectValue.isNotEmpty) {
+ switch (antiCrawlerConfig.captchaDetectType) {
+ case CaptchaDetectType.text:
+ return htmlString.contains(detectValue);
+ case CaptchaDetectType.regex:
+ try {
+ return RegExp(detectValue, caseSensitive: false, dotAll: true)
+ .hasMatch(htmlString);
+ } catch (e) {
+ KazumiLogger()
+ .w('Plugin: $name invalid captcha detect regex: $detectValue');
+ return false;
+ }
+ case CaptchaDetectType.xpath:
+ default:
+ final element = htmlElement ?? parse(htmlString).documentElement!;
+ return element.queryXPath(detectValue).node != null;
+ }
+ }
+
+ final element = htmlElement ?? parse(htmlString).documentElement!;
+ final List<String> detectionXpaths = [
+ antiCrawlerConfig.captchaImage,
+ antiCrawlerConfig.captchaButton,
+ ].where((x) => x.isNotEmpty).toList();
+ return detectionXpaths
+ .any((xpath) => element.queryXPath(xpath).node != null);
+ }
+
String buildFullUrl(String urlItem) {
if (urlItem.contains(baseUrl) ||
urlItem.contains(baseUrl.replaceAll('https', 'http'))) {
diff --git a/lib/providers/captcha/captcha_provider.dart b/lib/providers/captcha/captcha_provider.dart
index b11de430..8a141072 100644
--- a/lib/providers/captcha/captcha_provider.dart
+++ b/lib/providers/captcha/captcha_provider.dart
@@ -6,7 +6,7 @@ import 'package:kazumi/utils/logger.dart';
/// 验证码解决 Provider
///
-/// 支持两种独立的验证流程:
+/// 支持三种独立的验证流程:
///
/// **类型1:图片验证码**([loadForCaptcha] + [submitCaptcha])
/// 1. 初始化 WebView
@@ -21,8 +21,14 @@ import 'package:kazumi/utils/logger.dart';
/// 1. 初始化 WebView
/// 2. 加载搜索页面,注入 JS 脚本轮询验证按钮
/// 3. 检测到按钮后自动模拟点击
-/// 4. 按钮消失时,获取页面 Cookie 并保存到 [PluginCookieManager]
+/// 4. 按钮消失或页面跳转时,获取页面 Cookie 并保存到 [PluginCookieManager]
/// 5. 通过 [onVerified] 回调通知 UI 发起重新检索
+///
+/// **类型3:自定义 JS 验证**([loadForCustomScript])
+/// 1. 初始化 WebView
+/// 2. 加载搜索页面,注入规则中配置的 JS 验证脚本
+/// 3. 脚本调用 KazumiCaptcha.clicked/done 或返回 true 后完成验证
+/// 4. 获取页面 Cookie 并保存到 [PluginCookieManager]
class CaptchaProvider {
CaptchaWebviewController? _controller;
@@ -62,7 +68,8 @@ class CaptchaProvider {
/// [url] 要加载的页面地址
/// [captchaXpath] 验证码图片元素的 XPath
/// [inputXpath] 可选,验证码输入框的 XPath。如果提供,会在检测验证码前先触发输入框的 focus 事件
- Future<void> loadForCaptcha(String url, String captchaXpath, {String? inputXpath}) async {
+ Future<void> loadForCaptcha(String url, String captchaXpath,
+ {String? inputXpath}) async {
_pageUrl = url;
await _ensureInitialized();
if (_disposed || _controller == null) return;
@@ -100,28 +107,24 @@ class CaptchaProvider {
KazumiLogger().i('[CaptchaProvider] Submitting captcha code via interact');
- bool _handled = false;
+ bool handled = false;
Future<void> onDisappeared() async {
- if (_handled) return;
- _handled = true;
+ if (handled) return;
+ handled = true;
_disappearedSub?.cancel();
- final cookieString = await _controller!.getCookieString(_pageUrl);
- KazumiLogger().i('[CaptchaProvider] Captured cookies: $cookieString');
- if (cookieString.isNotEmpty) {
- await PluginCookieManager.instance
- .saveFromWebView(pluginName, _pageUrl, cookieString);
- KazumiLogger()
- .i('[CaptchaProvider] Cookies saved for plugin: $pluginName');
- }
- await _controller!.unloadPage();
+ final controller = _controller;
+ if (controller == null) return;
+ await _saveCookiesAndUnload(controller, pluginName);
onVerified();
}
+
_disappearedSub?.cancel();
_disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
onDisappeared();
});
- await _controller!.submitCaptchaInteract(captchaCode, inputXpath, buttonXpath);
+ await _controller!
+ .submitCaptchaInteract(captchaCode, inputXpath, buttonXpath);
}
/// 加载页面并自动点击验证按钮
@@ -129,7 +132,7 @@ class CaptchaProvider {
/// [url] 要加载的页面地址
/// [buttonXpath] 验证按钮元素的 XPath,检测到后自动点击
/// [pluginName] 规则名(用于保存 Cookie)
- /// [onVerified] 按钮消失(验证通过)后的回调
+ /// [onVerified] 验证通过后的回调
Future<void> loadForButtonClick({
required String url,
required String buttonXpath,
@@ -140,21 +143,16 @@ class CaptchaProvider {
await _ensureInitialized();
if (_disposed || _controller == null) return;
- bool _handled = false;
+ bool handled = false;
Future<void> onDisappeared() async {
- if (_handled) return;
- _handled = true;
+ if (handled) return;
+ handled = true;
_disappearedSub?.cancel();
- final cookieString = await _controller!.getCookieString(_pageUrl);
- KazumiLogger().i('[CaptchaProvider] (type2) Captured cookies: $cookieString');
- if (cookieString.isNotEmpty) {
- await PluginCookieManager.instance
- .saveFromWebView(pluginName, _pageUrl, cookieString);
- KazumiLogger()
- .i('[CaptchaProvider] (type2) Cookies saved for plugin: $pluginName');
- }
- await _controller!.unloadPage();
+ final controller = _controller;
+ if (controller == null) return;
+ await _saveCookiesAndUnload(controller, pluginName,
+ logPrefix: '(type2) ');
onVerified();
}
@@ -164,7 +162,41 @@ class CaptchaProvider {
});
await _controller!.loadPageForButtonClick(url, buttonXpath);
- KazumiLogger().i('[CaptchaProvider] (type2) Page loading for button click: $url');
+ KazumiLogger()
+ .i('[CaptchaProvider] (type2) Page loading for button click: $url');
+ }
+
+ Future<void> loadForCustomScript({
+ required String url,
+ required String script,
+ required String pluginName,
+ required void Function() onVerified,
+ }) async {
+ _pageUrl = url;
+ await _ensureInitialized();
+ if (_disposed || _controller == null) return;
+
+ bool handled = false;
+
+ Future<void> onDisappeared() async {
+ if (handled) return;
+ handled = true;
+ _disappearedSub?.cancel();
+ final controller = _controller;
+ if (controller == null) return;
+ await _saveCookiesAndUnload(controller, pluginName,
+ logPrefix: '(type3) ');
+ onVerified();
+ }
+
+ _disappearedSub?.cancel();
+ _disappearedSub = _controller!.onCaptchaDisappeared.listen((_) {
+ onDisappeared();
+ });
+
+ await _controller!.loadPageForCustomScript(url, script);
+ KazumiLogger()
+ .i('[CaptchaProvider] (type3) Page loading for custom script: $url');
}
Future<void> saveAndUnload(String pluginName) async {
@@ -174,14 +206,26 @@ class CaptchaProvider {
// between two awaits cannot cause a force-unwrap crash.
final controller = _controller;
if (controller == null || _pageUrl.isEmpty) return;
+ await _saveCookiesAndUnload(
+ controller,
+ pluginName,
+ logPrefix: 'on cancel ',
+ );
+ }
+
+ Future<void> _saveCookiesAndUnload(
+ CaptchaWebviewController controller,
+ String pluginName, {
+ String logPrefix = '',
+ }) async {
final cookieString = await controller.getCookieString(_pageUrl);
KazumiLogger()
- .i('[CaptchaProvider] Captured cookies on cancel: $cookieString');
+ .i('[CaptchaProvider] ${logPrefix}Captured cookies: $cookieString');
if (cookieString.isNotEmpty) {
await PluginCookieManager.instance
.saveFromWebView(pluginName, _pageUrl, cookieString);
- KazumiLogger()
- .i('[CaptchaProvider] Cookies saved on cancel for plugin: $pluginName');
+ KazumiLogger().i(
+ '[CaptchaProvider] ${logPrefix}Cookies saved for plugin: $pluginName');
}
await controller.unloadPage();
}
diff --git a/lib/request/config/api_endpoints.dart b/lib/request/config/api_endpoints.dart
index 76f98404..a1e0e8b5 100644
--- a/lib/request/config/api_endpoints.dart
+++ b/lib/request/config/api_endpoints.dart
@@ -3,7 +3,7 @@ class ApiEndpoints {
static const String version = '2.1.1';
/// 规则API级别
- static const int apiLevel = 6;
+ static const int apiLevel = 7;
/// 项目主页
static const String projectUrl = "https://kazumi.app/";
diff --git a/lib/webview/captcha/captcha_webview_controller.dart b/lib/webview/captcha/captcha_webview_controller.dart
index 803b23d8..26eb14b7 100644
--- a/lib/webview/captcha/captcha_webview_controller.dart
+++ b/lib/webview/captcha/captcha_webview_controller.dart
@@ -13,9 +13,9 @@ abstract class CaptchaWebviewController<T> {
/// used to determine if verification is successful after page navigation
bool captchaWasFound = false;
- /// For type-2 (auto-click button), we set this flag when the button click is triggered.
- /// Then on page navigation or DOM change, if this flag is set,
- /// we can confirm verification success without relying solely on captcha disappearance.
+ /// For automated flows, set when JavaScript has triggered a verification
+ /// action. A later navigation can then confirm success even if no captcha
+ /// element disappears in the current DOM.
bool buttonWasClicked = false;
final StreamController<String> captchaImageFoundController =
@@ -33,7 +33,7 @@ abstract class CaptchaWebviewController<T> {
/// 验证码图片 src 找到时触发(携带图片绝对 URL)
Stream<String> get onCaptchaImageFound => captchaImageFoundController.stream;
- /// 验证码图片从页面消失时触发
+ /// 验证完成时触发
Stream<void> get onCaptchaDisappeared => captchaDisappearedController.stream;
/// 调试日志
@@ -51,11 +51,16 @@ abstract class CaptchaWebviewController<T> {
/// 加载指定 URL,并注入监听验证按钮的 JS 脚本(类型2:自动点击验证按钮)
///
- /// 检测到 [buttonXpath] 元素后立即模拟点击;按钮消失时触发 [onCaptchaDisappeared]。
+ /// 检测到 [buttonXpath] 元素后立即模拟点击;按钮消失或页面跳转时触发 [onCaptchaDisappeared]。
/// [url] 要加载的页面地址
/// [buttonXpath] 验证按钮元素的 XPath 选择器
Future<void> loadPageForButtonClick(String url, String buttonXpath);
+ /// 加载指定 URL,并在页面内执行自定义验证脚本(类型3:自定义 JS 验证)
+ ///
+ /// 脚本可调用 window.KazumiCaptcha.log/clicked/done/fail。
+ Future<void> loadPageForCustomScript(String url, String script);
+
/// 在 WebView 内通过 JS 模拟输入验证码并模拟点击提交按钮
///
/// [captchaCode] 用户输入的验证码文本
diff --git a/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
index 66526881..29749b5f 100644
--- a/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_inappwebview_impl.dart
@@ -36,7 +36,8 @@ class CaptchaWebviewInAppWebviewImpl
onLoadStop: (controller, url) {
logEventController.add('[Captcha WebView] Load stop: $url');
if (buttonWasClicked && !captchaDisappearedController.isClosed) {
- KazumiLogger().i('[Captcha WebView] Button click → page navigated, verification done');
+ KazumiLogger().i(
+ '[Captcha WebView] Button click → page navigated, verification done');
buttonWasClicked = false;
captchaDisappearedController.add(null);
}
@@ -69,10 +70,13 @@ class CaptchaWebviewInAppWebviewImpl
handlerName: 'CaptchaStatusBridge',
callback: (args) {
final status = args.isNotEmpty ? args[0].toString() : '';
- logEventController.add('[Captcha WebView JS] Page captcha status: $status');
- if (status == 'absent' && captchaWasFound &&
+ logEventController
+ .add('[Captcha WebView JS] Page captcha status: $status');
+ if (status == 'absent' &&
+ captchaWasFound &&
!captchaDisappearedController.isClosed) {
- KazumiLogger().i('[Captcha WebView] Captcha gone after navigation (StatusBridge)');
+ KazumiLogger().i(
+ '[Captcha WebView] Captcha gone after navigation (StatusBridge)');
captchaWasFound = false;
captchaDisappearedController.add(null);
}
@@ -114,8 +118,9 @@ class CaptchaWebviewInAppWebviewImpl
Future<void> _addCaptchaUserScript() async {
if (_currentCaptchaImageXpath.isEmpty) return;
- final escapedXpath =
- _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedXpath = _currentCaptchaImageXpath
+ .replaceAll('\\', '\\\\')
+ .replaceAll("'", "\\'");
final escapedInputXpath =
_currentInputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
@@ -251,7 +256,8 @@ if (!_checkForCaptcha()) {
}
@override
- Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ Future<void> loadPage(String url, String captchaXpath,
+ {String? inputXpath}) async {
_currentCaptchaImageXpath = captchaXpath;
_currentInputXpath = inputXpath ?? '';
captchaWasFound = false;
@@ -263,13 +269,13 @@ if (!_checkForCaptcha()) {
.deleteAllCookies();
logEventController.add('[Captcha WebView] Cookies cleared before load');
} catch (_) {}
- await webviewController
- ?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ await webviewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
}
@override
Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
- _currentCaptchaImageXpath = ''; // disable captcha-image script on navigation
+ _currentCaptchaImageXpath =
+ ''; // disable captcha-image script on navigation
captchaWasFound = false;
buttonWasClicked = false;
_registerHandlers();
@@ -279,8 +285,70 @@ if (!_checkForCaptcha()) {
.deleteAllCookies();
logEventController.add('[Captcha WebView] Cookies cleared before load');
} catch (_) {}
- await webviewController
- ?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ await webviewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ }
+
+ @override
+ Future<void> loadPageForCustomScript(String url, String script) async {
+ _currentCaptchaImageXpath = '';
+ _currentInputXpath = '';
+ captchaWasFound = false;
+ buttonWasClicked = false;
+ _registerHandlers();
+ await _addCustomScriptUserScript(script);
+ try {
+ await PlatformCookieManager(const PlatformCookieManagerCreationParams())
+ .deleteAllCookies();
+ logEventController.add('[Captcha WebView] Cookies cleared before load');
+ } catch (_) {}
+ await webviewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
+ }
+
+ Future<void> _addCustomScriptUserScript(String script) async {
+ await webviewController?.removeAllUserScripts();
+
+ final source = '''
+(function() {
+ try {
+ window.KazumiCaptcha = {
+ log: function(message) {
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', String(message)); } catch(e) {}
+ },
+ clicked: function() {
+ try { window.flutter_inappwebview.callHandler('ButtonClickedBridge', ''); } catch(e) {}
+ },
+ done: function() {
+ try { window.flutter_inappwebview.callHandler('CaptchaGoneBridge', ''); } catch(e) {}
+ },
+ fail: function(message) {
+ try { window.flutter_inappwebview.callHandler('CaptchaLogBridge', 'Custom script failed: ' + String(message)); } catch(e) {}
+ }
+ };
+ window.KazumiCaptcha.log('CustomScript loaded on: ' + window.location.href);
+ if (!${script.trim().isEmpty ? 'false' : 'true'}) {
+ window.KazumiCaptcha.fail('empty captchaScript');
+ return;
+ }
+ var __kazumiResult = (function() {
+$script
+ })();
+ if (__kazumiResult === true) {
+ window.KazumiCaptcha.done();
+ }
+ } catch(e) {
+ try { window.KazumiCaptcha.fail(e && e.message ? e.message : e); } catch(e2) {}
+ }
+})();
+''';
+
+ await webviewController?.addUserScripts(
+ userScripts: [
+ UserScript(
+ source: source,
+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END,
+ ),
+ ],
+ );
}
Future<void> _addButtonClickUserScript(String buttonXpath) async {
@@ -410,8 +478,8 @@ if (!_checkAndClick()) {
@override
Future<void> unloadPage() async {
try {
- await webviewController
- ?.loadUrl(urlRequest: URLRequest(url: WebUri('about:blank')));
+ await webviewController?.loadUrl(
+ urlRequest: URLRequest(url: WebUri('about:blank')));
} catch (_) {}
}
diff --git a/lib/webview/captcha/impl/captcha_webview_linux_impl.dart b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
index 0d0cfdf0..b3a67005 100644
--- a/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_linux_impl.dart
@@ -7,11 +7,11 @@ import 'package:kazumi/utils/storage.dart';
import 'package:kazumi/utils/proxy_utils.dart';
import 'package:kazumi/webview/captcha/captcha_webview_controller.dart';
-class CaptchaWebviewLinuxImpl
- extends CaptchaWebviewController<Webview> {
+class CaptchaWebviewLinuxImpl extends CaptchaWebviewController<Webview> {
VoidCallback? _navigationListener;
String _currentCaptchaImageXpath = '';
String _buttonXpath = '';
+ String? _customScript;
@override
Future<void> init() async {
@@ -62,8 +62,8 @@ class CaptchaWebviewLinuxImpl
captchaDisappearedController.add(null);
}
} else if (msg.startsWith('captchaLog:')) {
- logEventController.add(
- '[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
+ logEventController
+ .add('[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
}
});
}
@@ -83,6 +83,8 @@ class CaptchaWebviewLinuxImpl
await _injectCaptchaScript();
} else if (_buttonXpath.isNotEmpty) {
await _injectButtonClickScript(_buttonXpath);
+ } else if (_customScript != null) {
+ await _injectCustomScript(_customScript!);
}
}
}
@@ -99,7 +101,7 @@ class CaptchaWebviewLinuxImpl
captchaDisappearedController.add(null);
}
}
- // Type-2: button was clicked; page navigation confirms verification.
+ // Automated verification marked a click; page navigation confirms success.
if (buttonWasClicked && !captchaDisappearedController.isClosed) {
logEventController.add(
'[Captcha WebView] Button click and page navigated, verification done');
@@ -110,9 +112,12 @@ class CaptchaWebviewLinuxImpl
}
Future<bool> _isCaptchaPresent() async {
- if (_currentCaptchaImageXpath.isEmpty || webviewController == null) return false;
- final escaped =
- _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ if (_currentCaptchaImageXpath.isEmpty || webviewController == null) {
+ return false;
+ }
+ final escaped = _currentCaptchaImageXpath
+ .replaceAll('\\', '\\\\')
+ .replaceAll("'", "\\'");
try {
final result = await webviewController!.evaluateJavaScript('''
(function() {
@@ -132,8 +137,9 @@ class CaptchaWebviewLinuxImpl
Future<void> _injectCaptchaScript() async {
if (_currentCaptchaImageXpath.isEmpty) return;
- final escapedXpath =
- _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedXpath = _currentCaptchaImageXpath
+ .replaceAll('\\', '\\\\')
+ .replaceAll("'", "\\'");
final script = '''
(function() {
@@ -144,11 +150,6 @@ class CaptchaWebviewLinuxImpl
var _captchaPoller = null;
var _disappearObserver = null;
- function _resolveSrc(node) {
- return node.getAttribute('src') || node.getAttribute('data-src') ||
- node.src || '';
- }
-
function _evalXpath() {
try {
var result = document.evaluate(
@@ -223,9 +224,11 @@ class CaptchaWebviewLinuxImpl
}
@override
- Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ Future<void> loadPage(String url, String captchaXpath,
+ {String? inputXpath}) async {
_currentCaptchaImageXpath = captchaXpath;
_buttonXpath = '';
+ _customScript = null;
buttonWasClicked = false;
captchaWasFound = false;
webviewController?.launch(url);
@@ -235,14 +238,70 @@ class CaptchaWebviewLinuxImpl
Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
_currentCaptchaImageXpath = '';
_buttonXpath = buttonXpath;
+ _customScript = null;
+ buttonWasClicked = false;
+ captchaWasFound = false;
+ webviewController?.launch(url);
+ }
+
+ @override
+ Future<void> loadPageForCustomScript(String url, String script) async {
+ _currentCaptchaImageXpath = '';
+ _buttonXpath = '';
+ _customScript = script;
buttonWasClicked = false;
captchaWasFound = false;
webviewController?.launch(url);
}
+ Future<void> _injectCustomScript(String script) async {
+ logEventController.add('[Captcha WebView] Injecting custom script');
+ final wrappedScript = '''
+(function() {
+ try {
+ window.KazumiCaptcha = {
+ log: function(message) {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:' + String(message));
+ },
+ clicked: function() {
+ window.webkit.messageHandlers.msgToNative.postMessage('buttonClicked:');
+ },
+ done: function() {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaGone:');
+ },
+ fail: function(message) {
+ window.webkit.messageHandlers.msgToNative.postMessage('captchaLog:Custom script failed: ' + String(message));
+ }
+ };
+ window.KazumiCaptcha.log('CustomScript injected on ' + window.location.href);
+ if (!${script.trim().isEmpty ? 'false' : 'true'}) {
+ window.KazumiCaptcha.fail('empty captchaScript');
+ return;
+ }
+ var __kazumiResult = (function() {
+$script
+ })();
+ if (__kazumiResult === true) {
+ window.KazumiCaptcha.done();
+ }
+ } catch(e) {
+ try { window.KazumiCaptcha.fail(e && e.message ? e.message : e); } catch(e2) {}
+ }
+})();
+''';
+ try {
+ final result = await webviewController?.evaluateJavaScript(wrappedScript);
+ logEventController
+ .add('[Captcha WebView] Custom script execute result: $result');
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] injectCustomScript error: $e');
+ logEventController
+ .add('[Captcha WebView] Custom script inject error: $e');
+ }
+ }
+
Future<void> _injectButtonClickScript(String buttonXpath) async {
- final escaped =
- buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escaped = buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
final script = '''
(function() {
window.webkit.messageHandlers.msgToNative.postMessage(
@@ -354,8 +413,7 @@ class CaptchaWebviewLinuxImpl
final cookies = await webviewController?.getAllCookies() ?? [];
final cookieString =
cookies.map((c) => '${c.name}=${c.value}').join('; ');
- logEventController
- .add('[Captcha WebView] Cookies: $cookieString');
+ logEventController.add('[Captcha WebView] Cookies: $cookieString');
return cookieString;
} catch (e) {
KazumiLogger().e('[Captcha WebView] getCookieString error: $e');
@@ -372,6 +430,7 @@ class CaptchaWebviewLinuxImpl
void dispose() {
_currentCaptchaImageXpath = '';
_buttonXpath = '';
+ _customScript = null;
buttonWasClicked = false;
captchaWasFound = false;
if (_navigationListener != null) {
diff --git a/lib/webview/captcha/impl/captcha_webview_windows_impl.dart b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
index de0ad013..34a7ce27 100644
--- a/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
+++ b/lib/webview/captcha/impl/captcha_webview_windows_impl.dart
@@ -14,6 +14,7 @@ class CaptchaWebviewWindowsImpl
String _currentInputXpath = '';
String _currentPageUrl = '';
String _buttonXpath = '';
+ String? _customScript;
@override
Future<void> init() async {
@@ -27,7 +28,7 @@ class CaptchaWebviewWindowsImpl
_headlessWebview!.webMessage.listen(_onWebMessage),
);
- // Inject captcha or button-click script when navigation completes
+ // Inject the active verification script when navigation completes.
_subscriptions.add(
_headlessWebview!.loadingState.listen((state) async {
if (state == LoadingState.navigationCompleted) {
@@ -37,13 +38,15 @@ class CaptchaWebviewWindowsImpl
await _injectCaptchaScript();
} else if (_buttonXpath.isNotEmpty) {
await _injectButtonClickScript(_buttonXpath);
+ } else if (_customScript != null) {
+ await _injectCustomScript(_customScript!);
}
}
}),
);
- // After a navigation, detect verification completion for both type-1
- // (captcha image gone) and type-2 (button was clicked, page navigated).
+ // After a navigation, detect verification completion for captcha-image
+ // and automated flows that marked a verification action as clicked.
_subscriptions.add(
_headlessWebview!.loadingState.listen((state) async {
if (state == LoadingState.navigationCompleted) {
@@ -57,8 +60,8 @@ class CaptchaWebviewWindowsImpl
}
}
if (buttonWasClicked && !captchaDisappearedController.isClosed) {
- logEventController
- .add('[Captcha WebView] Button click → page navigated, verification done');
+ logEventController.add(
+ '[Captcha WebView] Button click → page navigated, verification done');
buttonWasClicked = false;
captchaDisappearedController.add(null);
}
@@ -87,14 +90,18 @@ class CaptchaWebviewWindowsImpl
captchaDisappearedController.add(null);
}
} else if (msg.startsWith('captchaLog:')) {
- logEventController.add('[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
+ logEventController
+ .add('[Captcha WebView JS] ${msg.replaceFirst('captchaLog:', '')}');
}
}
Future<bool> _isCaptchaPresent() async {
- if (_currentCaptchaImageXpath.isEmpty || _headlessWebview == null) return false;
- final escaped =
- _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ if (_currentCaptchaImageXpath.isEmpty || _headlessWebview == null) {
+ return false;
+ }
+ final escaped = _currentCaptchaImageXpath
+ .replaceAll('\\', '\\\\')
+ .replaceAll("'", "\\'");
try {
final result = await _headlessWebview!.executeScript('''
(function() {
@@ -114,8 +121,9 @@ class CaptchaWebviewWindowsImpl
Future<void> _injectCaptchaScript() async {
if (_currentCaptchaImageXpath.isEmpty) return;
- final escapedXpath =
- _currentCaptchaImageXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escapedXpath = _currentCaptchaImageXpath
+ .replaceAll('\\', '\\\\')
+ .replaceAll("'", "\\'");
final escapedInputXpath =
_currentInputXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
@@ -128,11 +136,6 @@ class CaptchaWebviewWindowsImpl
var _captchaPoller = null;
var _disappearObserver = null;
- function _resolveSrc(node) {
- return node.getAttribute('src') || node.getAttribute('data-src') ||
- node.src || '';
- }
-
function _evalXpath() {
try {
var result = document.evaluate(
@@ -238,10 +241,12 @@ class CaptchaWebviewWindowsImpl
}
@override
- Future<void> loadPage(String url, String captchaXpath, {String? inputXpath}) async {
+ Future<void> loadPage(String url, String captchaXpath,
+ {String? inputXpath}) async {
_currentCaptchaImageXpath = captchaXpath;
_currentInputXpath = inputXpath ?? '';
_buttonXpath = '';
+ _customScript = null;
buttonWasClicked = false;
_currentPageUrl = url;
captchaWasFound = false;
@@ -252,15 +257,73 @@ class CaptchaWebviewWindowsImpl
Future<void> loadPageForButtonClick(String url, String buttonXpath) async {
_currentCaptchaImageXpath = '';
_buttonXpath = buttonXpath;
+ _customScript = null;
buttonWasClicked = false;
_currentPageUrl = url;
captchaWasFound = false;
await _headlessWebview?.loadUrl(url);
}
+ @override
+ Future<void> loadPageForCustomScript(String url, String script) async {
+ _currentCaptchaImageXpath = '';
+ _currentInputXpath = '';
+ _buttonXpath = '';
+ _customScript = script;
+ buttonWasClicked = false;
+ _currentPageUrl = url;
+ captchaWasFound = false;
+ await _headlessWebview?.loadUrl(url);
+ }
+
+ Future<void> _injectCustomScript(String script) async {
+ logEventController.add('[Captcha WebView] Injecting custom script');
+ final wrappedScript = '''
+(function() {
+ try {
+ window.KazumiCaptcha = {
+ log: function(message) {
+ window.chrome.webview.postMessage('captchaLog:' + String(message));
+ },
+ clicked: function() {
+ window.chrome.webview.postMessage('buttonClicked:');
+ },
+ done: function() {
+ window.chrome.webview.postMessage('captchaGone:');
+ },
+ fail: function(message) {
+ window.chrome.webview.postMessage('captchaLog:Custom script failed: ' + String(message));
+ }
+ };
+ window.KazumiCaptcha.log('CustomScript injected on ' + window.location.href);
+ if (!${script.trim().isEmpty ? 'false' : 'true'}) {
+ window.KazumiCaptcha.fail('empty captchaScript');
+ return;
+ }
+ var __kazumiResult = (function() {
+$script
+ })();
+ if (__kazumiResult === true) {
+ window.KazumiCaptcha.done();
+ }
+ } catch(e) {
+ try { window.KazumiCaptcha.fail(e && e.message ? e.message : e); } catch(e2) {}
+ }
+})();
+''';
+ try {
+ final result = await _headlessWebview?.executeScript(wrappedScript);
+ logEventController
+ .add('[Captcha WebView] Custom script execute result: $result');
+ } catch (e) {
+ KazumiLogger().e('[Captcha WebView] injectCustomScript error: $e');
+ logEventController
+ .add('[Captcha WebView] Custom script inject error: $e');
+ }
+ }
+
Future<void> _injectButtonClickScript(String buttonXpath) async {
- final escaped =
- buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
+ final escaped = buttonXpath.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
final script = '''
(function() {
window.chrome.webview.postMessage('captchaLog:ButtonClickScript injected on ' + window.location.href);
@@ -379,8 +442,8 @@ class CaptchaWebviewWindowsImpl
@override
Future<void> unloadPage() async {
try {
- await _headlessWebview?.executeScript(
- "window.location.href = 'about:blank';");
+ await _headlessWebview
+ ?.executeScript("window.location.href = 'about:blank';");
} catch (e) {
KazumiLogger().d('[Captcha WebView] unloadPage skipped: $e');
}
@@ -391,6 +454,7 @@ class CaptchaWebviewWindowsImpl
_currentCaptchaImageXpath = '';
_currentInputXpath = '';
_buttonXpath = '';
+ _customScript = null;
buttonWasClicked = false;
_currentPageUrl = '';
for (final s in _subscriptions) {