【问题标题】:Parsing iframe HTML code to get just the src attribute解析 iframe HTML 代码以获取 src 属性
【发布时间】:2020-11-28 19:29:38
【问题描述】:

我希望能够采用如下 Iframe HTML 代码...

<iframe src="https://example.com" width="100" height="100"></iframe>

从中获取src 属性:https://example.com

我需要在 javascript 中获取 src 属性。

我已尝试执行以下操作:

var iframeCode = `<iframe src="https://example.com" width="100" height="100"></iframe>`
document.getElementById("tmpElement").outerHTML = iframeCode
var src = document.getElementById("tmpElement").childNodes[0].src

它有效,但这种方法存在安全漏洞。如果我在 iframe 代码中设置的页面包含 javascript,它将执行。 虽然这是正常行为,但我需要帮助找到一个解决方案,该解决方案要么不执行 javascript,要么在不加载 src 的情况下获取iframe(这可能使用正则表达式,可能吗?但我不是正则表达式专家。)

提前谢谢你。

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    您可以使用 DOMParser,它可以将 HTML 字符串转换为文档,而不会执行不安全的代码(如脚本或内联处理程序):

    const str = '<iframe src="https://example.com" width="100" height="100"></iframe>';
    const doc = new DOMParser().parseFromString(str, 'text/html');
    console.log(doc.body.children[0].src);

    【讨论】:

    • 谢谢!这非常有帮助,并且解决了我的问题。我会在 7 分钟内标记为答案,如果可以的话
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2015-01-18
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多