createFragment 方法

DocumentFragment createFragment(
  1. String? html,
  2. {NodeValidator? validator,
  3. NodeTreeSanitizer? treeSanitizer}
)

从HTML片段创建DocumentFragment,并确保它遵循由validator或treeSanitizer指定的清理规则。

如果默认验证行为过于严格,则应创建一个新的NodeValidator,无论是扩展还是包装默认验证器并覆盖验证API。

treeSanitizer用于遍历生成的节点树并进行清理。也可以提供自定义treeSanitizer以执行特殊验证规则,但由于API实现更复杂,因此不建议这么做。

返回的树仅保证包含由提供的validator允许的节点和属性。

另请参阅

实现

DocumentFragment createFragment(String? html,
    {NodeValidator? validator, NodeTreeSanitizer? treeSanitizer}) {
  if (treeSanitizer == null) {
    if (validator == null) {
      if (_defaultValidator == null) {
        _defaultValidator = new NodeValidatorBuilder.common();
      }
      validator = _defaultValidator;
    }
    if (_defaultSanitizer == null) {
      _defaultSanitizer = new _ValidatingTreeSanitizer(validator!);
    } else {
      _defaultSanitizer!.validator = validator!;
    }
    treeSanitizer = _defaultSanitizer;
  } else if (validator != null) {
    throw new ArgumentError(
        'validator can only be passed if treeSanitizer is null');
  }

  if (_parseDocument == null) {
    _parseDocument = document.implementation!.createHtmlDocument('');
    _parseRange = _parseDocument!.createRange();

    // Workaround for Safari bug. Was also previously Chrome bug 229142
    // - URIs are not resolved in new doc.
    BaseElement base = _parseDocument!.createElement('base') as BaseElement;
    base.href = document.baseUri!;
    _parseDocument!.head!.append(base);
  }

  // TODO(terry): Fixes Chromium 50 change no body after createHtmlDocument()
  if (_parseDocument!.body == null) {
    _parseDocument!.body =
        _parseDocument!.createElement("body") as BodyElement;
  }

  Element contextElement;
  if (this is BodyElement) {
    contextElement = _parseDocument!.body!;
  } else {
    contextElement = _parseDocument!.createElement(tagName);
    _parseDocument!.body!.append(contextElement);
  }
  DocumentFragment fragment;
  if (Range.supportsCreateContextualFragment &&
      _canBeUsedToCreateContextualFragment) {
    _parseRange!.selectNodeContents(contextElement);
    // createContextualFragment expects a non-nullable html string.
    // If null is passed, it gets converted to 'null' instead.
    fragment = _parseRange!.createContextualFragment(html ?? 'null');
  } else {
    contextElement._innerHtml = html;

    fragment = _parseDocument!.createDocumentFragment();
    while (contextElement.firstChild != null) {
      fragment.append(contextElement.firstChild!);
    }
  }
  if (contextElement != _parseDocument!.body) {
    contextElement.remove();
  }

  treeSanitizer!.sanitizeTree(fragment);
  // Copy the fragment over to the main document (fix for 14184)
  document.adoptNode(fragment);

  return fragment;
}