In HTML, the <iframe> tag can specify the content to be displayed within the inline frame using the src and srcdoc attributes. Although both attributes serve a similar purpose—displaying HTML code within the <iframe>—they have some key differences:
-
Definition and Purpose:
- The
srcdocattribute allows directly embedding HTML content within the<iframe>tag. Withsrcdoc, you can include HTML code directly in the attribute without requiring a URL. - The
srcattribute is typically used to specify a URL of an external page, but it can also embed data using thedata:protocol. When usingsrc="data:text/html,...", you are creating a data URL that embeds the HTML content directly within the URL.
- The
-
Security:
- Using
srcdocis relatively safer because it does not depend on external resources, making it less susceptible to man-in-the-middle (MITM) attacks. Additionally, withsrcdoc, you have more precise control over the content since it is directly embedded. - Using the
data:protocol with thesrcattribute also avoids the need to load external resources, but creating a data URL may involve more complex encoding processes, and if mishandled, it could introduce injection attack risks.
- Using
-
Compatibility and Use Cases:
- The
srcdocattribute is well-supported in newer browsers but may not be supported in some older browsers. - The
data:protocol is widely supported in most modern browsers, but because the content is directly part of the URL, it may encounter URL length limitations.
- The
Practical Example
Suppose you need to display a simple HTML page within an <iframe>, such as one containing only the text "Hello, world!".
Example using the srcdoc attribute:
html<iframe srcdoc="<p>Hello, world!</p>"/></iframe>
Example using the src attribute with the data: protocol:
html<iframe src="data:text/html;base64,PHA+SGVsbG8sIHdvcmxkITwvcD4="/></iframe>
In this example, the HTML content is first converted to base64 encoding and then included as part of the URL. Although effective, this method increases implementation complexity.
In summary, the use of srcdoc and src attributes depends on specific application scenarios and browser compatibility requirements. In most cases, if you want to directly embed short HTML code within the <iframe>, srcdoc is a more direct and secure choice.