为什么这个过滤器没有输出IFRAME?

时间:2014-06-27 03:14:42

标签: javascript angularjs angularjs-filter

我试图自动为用户生成的内容嵌入YouTube视频。我的过滤器会查找一般的链接,然后测试它们以查看它们是否是有效的YouTube视频。如果是,则应使用标准iframe代码嵌入视频。如果没有,它只是一个链接。但是,过滤器根本不输出iframe代码。我假设这有一些东西可以阻止跨站点脚本攻击,但我不知道如何绕过它。

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

使用中:

<span ng-bind-html="p.body | noHTML | newlines | parseUrls:'_blank'"></span>

1 个答案:

答案 0 :(得分:1)

Angular要求您通过“&#39; sce”传递HTML。 (严格的上下文转义)提供者。

Documentation on the SCE provider here

所以它看起来像这样(未经测试但理论上它应该)

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', ['$sce', function() {
    //with protocol
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;
    return function(text, target, otherProp) {        
        if (text == null) {
            return "";
        }
        angular.forEach(text.match(urlPattern), function(url) {
            if(ytVidId(url)){
                text = text.replace(url, $sce.trustAs('html', '<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, $sce.trustAs('html', '<a target="' + target + '" href='+ url + '>' + url + '</a>'));
            }    

        });
        return text;        
    };
}])`
相关问题