getBase64Screenshot static method

Future<String> getBase64Screenshot()

Implementation

static Future<String> getBase64Screenshot() async {
  try {
    await loadHtml2Canvas();

    final html2canvasFunc =
        web.window.getProperty("html2canvas".toJS) as JSFunction?;
    if (html2canvasFunc == null) {
      debugPrint("html2canvas is not defined even after loading.");
    }

    final body = web.document.body;
    if (body == null) {
      debugPrint("document.body is null. Cannot capture screenshot.");
    }

    final completer = Completer<JSAny>();

    // Get the Promise from html2canvas
    final canvasPromise =
        html2canvasFunc?.callAsFunction(null, body) as Promise;

    // Handle Promise resolution/rejection
    canvasPromise.then(
      ((JSAny result) {
        completer.complete(result);
      }).toJS,
      ((JSAny error) {
        completer.completeError(error);
      }).toJS,
    );

    // Wait for the Promise to resolve
    final canvas = await completer.future;

    if (canvas.isNull) {
      debugPrint("html2canvas returned null canvas.");
    }
    final dataUrl = (canvas as JSObject)
        .callMethod('toDataURL'.toJS, ['image/png'.toJS].toJS)
        .toString();

    if (dataUrl.isEmpty) {
      debugPrint("Failed to convert canvas to data URL.");
      return "";
    }
    return dataUrl.toString();
  } catch (error, stackTrace) {
    debugPrint("Error in getBase64Screenshot: $error");
    debugPrint("Stack trace: $stackTrace");
    return "";
  }
}