Meteor.js安全地嵌入iframe

时间:2016-03-09 21:13:01

标签: javascript regex iframe meteor embed

我有一个包含聊天的meteor.js应用。我们需要允许用户从youtube和soundcloud发布嵌入代码。安全。

我使用djedi:sanitize-html-client来清理用户输入,而不是包含" youtube"和" soundcloud.com"

因此,对于YouTube,我使用了该用户输入字符串,例如



<iframe width="560" height="315" src="https://www.youtube.com/embed/B65pLsah3XE" frameborder="0" allowfullscreen></iframe>
&#13;
&#13;
&#13;

,然后将其拆分为空格,并使用此RegEx循环遍历数组以查找有效的URL:

&#13;
&#13;
var pattern = new RegExp("(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?");
&#13;
&#13;
&#13;

之后,如果找到了有效的网址,我会在代码中重建iframe html,按常规插入到Mongo中,并在聊天窗口中显示。这部分正在运作。

但是这种方法对于soundcloud嵌入代码不起作用,例如:

&#13;
&#13;
<iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/227010461&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe>
&#13;
&#13;
&#13;

RegEx在该soundcloud iframe代码中找不到匹配项。

所以,我的问题是:我如何从soundcloud embed html中注册这两个网址,或者在Meteor.js中是否有一种安全的方式来允许嵌入iframe。

1 个答案:

答案 0 :(得分:1)

你可以使用这个JS代码:

var getHostname = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l.hostname;
};

并在您的代码中使用它:

getHostname("https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/227010461&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true")

返回:

  

“w.soundcloud.com”

相关问题