extractIslandProps function

Map<String, dynamic> extractIslandProps(
  1. Element element
)

Extracts decoded props from an island placeholder element.

Reads the bloomPropsAttribute (data-bloom-props) attribute on element. If absent or unparseable, looks for a child <script type="application/json"> element inside element.

Handles raw JSON strings, URI-encoded JSON strings, and malformed syntax without throwing. Returns an empty map if no props payload is present or if decoding fails.

final props = extractIslandProps(element);
print('Product ID: ${props["productId"]}');

Implementation

Map<String, dynamic> extractIslandProps(web.Element element) {
  final attr = element.getAttribute(bloomPropsAttribute);
  if (attr != null && attr.trim().isNotEmpty) {
    final trimmed = attr.trim();
    try {
      final decoded = jsonDecode(trimmed);
      if (decoded is Map) {
        return decoded.map((k, v) => MapEntry(k.toString(), v));
      }
    } catch (_) {
      try {
        final uriDecoded = Uri.decodeComponent(trimmed);
        final decoded = jsonDecode(uriDecoded);
        if (decoded is Map) {
          return decoded.map((k, v) => MapEntry(k.toString(), v));
        }
      } catch (_) {}
    }
  }

  try {
    final script = element.querySelector('script[type="application/json"]');
    if (script != null) {
      final content = script.textContent?.trim();
      if (content != null && content.isNotEmpty) {
        final decoded = jsonDecode(content);
        if (decoded is Map) {
          return decoded.map((k, v) => MapEntry(k.toString(), v));
        }
      }
    }
  } catch (_) {}

  return const <String, dynamic>{};
}