Parsing iframe HTML code to get just the src attribute

Viewed 272

I want to be able to take Iframe HTML code like the following...

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

and from it just get the src attribute: https://example.com

I will need to get the src attribute in javascript.

I have tried doing the following:

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

It works, but there is a security flaw with this approach. If the page I set in the iframe code contains javascript, it would execute. While this is normal behaviour, I need help to find a solution which will either not execute the javascript or get the src without loading the iframe (this may be possible with regex, possibly?, but I am no expert at regex.)

Thank you in advance.

1 Answers

You could use DOMParser, which can turn an HTML string into a document without any possibility of executing unsafe code (like scripts or inline handlers):

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

Related