createFragment 方法
- String? html, {
- NodeValidator? validator,
- 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;
}