1

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

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

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

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

我尝试过执行以下操作:

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,要么在不加载 iframe 的情况下获取 src(这可能使用正则表达式,可能吗?但我不是正则表达式专家。)

先感谢您。

4

1 回答 1

3

您可以使用 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);

于 2020-11-28T19:32:33.927 回答