2015-04-15 38 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

完成,感謝您的反饋:) –