What is the use of srcdoc Attribute in <iframe> Tags ?

The “srcdoc” attribute in <iframe> tags is used to embed HTML content directly within the iframe element. Instead of loading content from an external URL specified in the “src” attribute, the “srcdoc” attribute allows developers to define the HTML content inline within the iframe tag itself. ‘

Note: This attribute is particularly useful for embedding dynamic or small HTML documents directly into a webpage without the need for an external file.

Syntax

<iframe srcdoc="HTML_content"></iframe>
Key Point Description
Inline HTML Content The “srcdoc” attribute allows developers to specify the HTML content that should be displayed within the iframe directly within the attribute value.
Security Considerations Care should be taken when using “srcdoc” to ensure that the embedded HTML content does not pose security risks such as XSS (cross-site scripting) attacks.
Compatibility While widely supported in modern browsers, the “srcdoc” attribute may not be supported in older browsers or certain contexts, so fallback mechanisms may be necessary.
Dynamic Content The “srcdoc” attribute enables developers to dynamically generate or manipulate HTML content within iframes, providing flexibility and interactivity in web applications.

Features

  • Basic Usage: Define the HTML content to be displayed within the iframe using the “srcdoc” attribute.
<iframe srcdoc="<html><body><h1>Hello, World!</h1></body></html>"></iframe>
  • Dynamic Content: The content specified in the “srcdoc” attribute can be dynamically generated or modified using JavaScript, allowing for dynamic updates or interactions within the iframe.
  • Fallback Mechanisms: To provide compatibility with older browsers or situations where the “srcdoc” attribute is not supported, developers can include a fallback URL using the “src” attribute.