我有一个包含聊天功能的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>
,然后将其按空格分割,并循环遍历数组以使用以下正则表达式查找有效的 url:
var pattern = new RegExp("(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
之后,如果找到有效的网址,我会在代码中重建 iframe html,照常插入到 Mongo 中,然后将其显示在聊天窗口中。这部分正在工作。
但是这种方法不适用于 soundcloud 嵌入代码,例如:
<iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/227010461&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
RegEx 在 soundcloud iframe 代码中找不到匹配项。
所以,我的问题是:我如何从 soundcloud 嵌入 html 中正则表达式这两个 url,或者 Meteor.js 中是否有一种安全的方法来允许嵌入 iframe。
最佳答案
你可以使用这个 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&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true")
返回:
"w.soundcloud.com"
关于javascript - Meteor.js 安全地嵌入 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902727/