I have a filter set up to automatically embed YouTube videos for user-generated content by searching for links and verifying if they are valid YouTube videos. If they are, the video should be embedded using standard iframe code; otherwise, it remains just a link. However, the filter is not outputting the expected iframe code. It seems like there might be security measures in place to prevent cross-site scripting attacks, but I'm unsure how to work around this issue.
function ytVidId(url) {
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp.$1 : false;
}
myapp.filter('parseUrls', function() {
//with protocol
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
return function(text, target, otherProp) {
if (text == null) {
return "";
}
angular.forEach(text.match(urlPattern), function(url) {
if(ytVidId(url)){
text = text.replace(url, '<div class="video-container"><iframe src="//www.youtube.com/embed/'+ ytVidId(url) +'" frameborder="0" width="560" height="315"></iframe></div>');
}else{
text = text.replace(url, '<a target="' + target + '" href='+ url + '>' + url + '</a>');
}
});
return text;
};
})
Example usage:
<span ng-bind-html="p.body | noHTML | newlines | parseUrls:'_blank'"></span>