init static method
Future
init(
- WpClientInterface wpClient, {
- String? wppJsContent,
- String? wppVersion,
- Map<
String, dynamic> ? config,
make sure to call init to Initialize Wpp
Implementation
static Future init(
WpClientInterface wpClient, {
String? wppJsContent,
String? wppVersion,
Map<String, dynamic>? config,
}) async {
String wppUrl;
if (wppVersion != null && wppVersion.isNotEmpty) {
wppUrl =
"https://github.com/wppconnect-team/wa-js/releases/download/$wppVersion/wppconnect-wa.js";
} else {
wppUrl =
"https://github.com/wppconnect-team/wa-js/releases/latest/download/wppconnect-wa.js";
}
// Check if WPP is already present on the page (to avoid double injection)
// We only check for presence, not 'isReady' here, to skip injection correctly
final isWppPresent = await wpClient.evaluateJs(
'''typeof window.WPP !== 'undefined';''',
tryPromise: false,
);
if (isWppPresent != true && isWppPresent?.toString() != "true") {
// Check if we are on the correct page before injection
final currentUrl = await wpClient.evaluateJs("window.location.href", tryPromise: false);
if (currentUrl != null && !currentUrl.toString().contains("web.whatsapp.com")) {
WhatsappLogger.log("Not on WhatsApp Web page ($currentUrl), loading ${WhatsAppMetadata.whatsAppURL}...");
await wpClient.loadUrl(WhatsAppMetadata.whatsAppURL);
// Wait for page load
await Future.delayed(const Duration(seconds: 5));
}
WhatsappLogger.log("WPP not found, fetching and injecting script content...");
try {
String content;
if (wppJsContent != null) {
content = wppJsContent;
} else if (_cachedWppJsContent != null && _cachedVersion == (wppVersion ?? 'latest')) {
content = _cachedWppJsContent!;
} else {
content = await http
.read(Uri.parse(wppUrl))
.timeout(const Duration(seconds: 30));
_cachedWppJsContent = content;
_cachedVersion = wppVersion ?? 'latest';
}
// Inject the library as a string
await wpClient.injectJs(content);
WhatsappLogger.log("WPP script content injected, length: ${content.length}");
// Give it a moment to parse and initialize
await Future.delayed(const Duration(seconds: 1));
} catch (e) {
throw WhatsappException(
exceptionType: WhatsappExceptionType.failedToConnect,
message: "Failed to fetch or inject WPP script: $e",
);
}
} else {
WhatsappLogger.log("WPP already present on page, skipping injection");
}
// Wait for WPP to be fully initialized and Webpack modules to be ready
if (!await _waitForWppReady(wpClient, 60)) {
throw const WhatsappException(
exceptionType: WhatsappExceptionType.failedToConnect,
message: "Timed out waiting for WPP to be ready",
);
}
// Modern WA-JS configuration
await _configureWpp(wpClient, config: config);
WhatsappLogger.log("WPP initialized and configured");
}