How to create shadow DOM programmatically in Dart?

£可爱£侵袭症+ 提交于 2020-01-02 18:58:19

问题


I'm trying to implement the following JS code in Dart way:

Code is taken from here: http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/

<div id="host">Host node</div>
<script>
var root = document.querySelector('#host').createShadowRoot();
root.innerHTML = '<style>' + 
    'button {' + 
      'color: green;' + 
    '}' +
    '</style>' +
    '<content></content>';
</script>

I have no doubt that in JS it works ok, but in Dart it fails. As we know the only one dart script per document is allowed, so I was forced to place it to the shared dart file:

main.dart

import 'dart:html';
void main() {
  querySelector('#host').createShadowRoot().appendHtml('<style>' +
    'button {' +
      'color: green;' +
    '}' +
    '</style>' +
    '<content></content>');
}

If we try to append any other html tags such as div, ul etc everything works ok. However in case of style and content it differs. I get the warning:

Removing disallowed element <CONTENT>
Removing disallowed element <STYLE>

Please, tell me why?

Update:

@GünterZöchbauer Regarding passing the NodeValidatorBuilder() to appendHtml() method. Please, see the picture:

Final result:

var validator = new NodeValidatorBuilder.common()
  ..allowElement('content', attributes: ['some-attribute', 'some-other'])
  ..allowElement('style');
querySelector('#host').createShadowRoot()
..append(document.body.createFragment('<style>' +
  'button {' +
    'color: green;' +
  '}' +
  '</style>' +
  '<content></content>', validator: validator))
// For illustrative purposes, add the button with some text to test styles
..querySelector('content').append(new ButtonElement()..text = 'Button');

回答1:


This is some default XSS prevention in dart:html. You need to pass a NodeValidator to appendHtml which specifies which elements and attributes are allowed.

var validator new NodeValidatorBuilder.common()
  ..allowElement('content', attributes: ['some-attribute', 'some-other'])
  ..allowElement('style');

... .append(document.body.createFragment(
    '...some html...', validator: validator));


来源:https://stackoverflow.com/questions/29644253/how-to-create-shadow-dom-programmatically-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!