Timur Fayzrakhmanov
Timur Fayzrakhmanov

Reputation: 19587

How to create shadow DOM programmatically in Dart?

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: enter image description here

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');

Upvotes: 2

Views: 286

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657278

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));

Upvotes: 2

Related Questions