2015-04-15 36 views
2

我试图实现达特方式下面的JS代码:如何在Dart中以编程方式创建阴影DOM?

代码就是从这里取: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> 

我毫不怀疑,在JS它工作正常,但在DART失败。 我们知道每个文档只有一个镖脚本是允许的,所以我不得不将其放置到共享文件镖:

main.dart

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

如果我们尝试添加其他任何html标记如div,ul等一切正常。然而,在stylecontent的情况下,它有所不同。我收到警告:

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

请告诉我为什么?

更新:

@GünterZöchbauer关于传递NodeValidatorBuilder()appendHtml()方法。请看到的景象: enter image description here

最终结果:

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

回答

2

这是一些默认XSS预防dart:html。您需要将一个NodeValidator传递给appendHtml,它指定允许哪些元素和属性。

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

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

嗯...,appendHtml()可以采用只有一个参数。如果是的话在哪里放置验证器变量? –

+0

我从http://stackoverflow.com/a/24002691/217408偷了它我很确定我当时试过。也许你需要使用另一种方法。我会看看... –

+0

完成,感谢您的反馈:) –