openContent method

void openContent(
  1. String content, {
  2. ContentType? contentType,
})

Opens the content.

Throws StateError if called inside a browser.

Example

import 'package:universal_html/controller.dart';

void main() {
  final controller = WindowController();
  controller.openContent('<html><body>Hello</body></html>');
}

Implementation

void openContent(String content, {ContentType? contentType}) {
  if (isTopLevelWindowInsideBrowser) {
    throw StateError('Failed to mutate the main window inside a browser');
  }

  if (contentType == null) {
    // Sniff MIME.
    final mime = const ContentTypeSniffer().sniffMime(content);
    if (mime != null) {
      contentType = ContentType.parse(mime);
    }
  }

  // Use HTML MIME by default
  contentType ??= ContentType.html;

  // Construct a new window
  final window = windowBehavior.newWindow(windowController: this);

  if (contentType.subType == 'xml' || contentType.subType == 'xhtml') {
    // Parse XML.
    final parsedDocument = parsing.parseXmlDocument(content, window: window);

    // Transfer XML nodes to the window.
    // (This is not necessary product what we want. Fix if you have time.)
    final documentElement = window.document.documentElement;
    for (var child in documentElement!.children.toList()) {
      child.remove();
    }
    for (var child in parsedDocument.documentElement!.children.toList()) {
      documentElement.append(child);
    }
  } else {
    // Parse HTML.
    final parsedDocument = parsing.parseHtmlDocument(content, window: window);

    // Transfer HTML nodes to the window.
    // (This is not necessary product what we want. Fix if you have time.)
    final documentElement = window.document.documentElement;
    for (var child in documentElement!.children.toList()) {
      child.remove();
    }
    for (var child in parsedDocument.documentElement!.children.toList()) {
      documentElement.append(child);
    }
  }

  // Set current window.
  this.window = window;
}