Issue
is there a way to inject HTML without filtering the src attribute in Dart (no security needed in context), I’ve tried setInnerHtml, but it doesn’t let src pass it…
here’s the div I’m adding html in:
<div id="output">
<!--here goes messages-->
</div>
here’s my dart code:
import 'dart:html';
import 'dart:async';
InputElement input = querySelector("#textInput");
var output = querySelector("#output");
var buttonSend = querySelector("#send");
var buttonImg = querySelector("#url");
var buttonVideo = querySelector("#video");
Future<Null> main() async {
//send custom message
buttonSend.onClick.listen((MouseEvent event) async{
addContent(input.value);
});
//send img
buttonImg.onClick.listen((MouseEvent event) async{
addContent(getPrefabImg(input.value));
});
//send video
buttonVideo.onClick.listen((MouseEvent event) async{
addContent(getPrefabVideo(input.value));
});
}
//if user use a prefab img
String getPrefabImg(url) {
return "<img class='prefabImg' src='" + url + "'>";
}
//if user use a prefab video
String getPrefabVideo(url) {
return "<iframe class='prefabVideo'' src='" + url + "' frameborder='0' allowfullscreen></iframe>";
}
//reset input and add content
void addContent(value){
output.setInnerHtml(value + output.innerHtml);
input.value = null;
}
Solution
To create and inject HTML into the DOM without a NodeTreeSanitizer
, you will need to switch from using HTML String
s to using Dart’s Node
objects. Picking a couple of functions from your code as an example, you can change them to something like;
ImageElement getPrefabImg(String url) {
return new ImageElement(src: url)..classes.add('prefabImage');
}
void addContent(Node node) {
output.nodes.insert(0, node);
input.value = null;
}
But with your current code you can easily add a NodeTreeSanitizer
like so;
void addContent(String value) {
output.insertAdjacentHtml(
'afterBegin', value, treeSanitizer: NodeTreeSanitizer.trusted);
input.value = null;
}
Answered By – stwupton
Answer Checked By – Clifford M. (FlutterFixes Volunteer)