Embedding Another HTML Document
The iframe element embeds another HTML document within the existing one.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<a href="http://google.com" target="frame">google.com</a>
<a href="http://java2s.com" target="frame">java2s.com</a>
<iframe name="myframe" width="300" height="100">
</iframe>
</body>
</html>
The code created an iframe with a name attribute value of frame. A browsing context called myframe is created.
The width and height attributes specify the size in pixels. We can use this browsing context with the target attribute of other elements:a, form, button, input, and base.
The src attribute specifies a URL that should be loaded and displayed in the iframe initially. The srcdoc attribute allows you to define an HTML document to display inline.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<iframe src="http://google.com" width="300" height="100">
</iframe>
</body>
</html>
HTML5 introduces two new attributes for the iframe element. The first, seamless, instructs the browser to display the iframe contents as though they were an integral part of the main HTML document.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<iframe seamless src="http://google.com" width="300" height="100">
</iframe>
</body>
</html>
The second attribute, sandbox, applies restrictions to the HTML document. When the attribute is applied with no value, like this:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<iframe sandbox src="http://google.com" width="300" height="100">
</iframe>
</body>
</html>
The following are disabled for sandbox:
- scripts
- forms
- plugins
- links that target other browsing contexts
The content in the iframe is treated as though it originated from a different source than the rest of the HTML document. This enforces additional security measures.
You can enable individual features by defining values for the sandbox attribute, like this:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<iframe sandbox="allow-forms" src="http://google.com" width="300" height="100">
</iframe>
</body>
</html>
The set of values that can be used with sandbox
Value | Description |
---|---|
allow-forms | Enables forms |
allow-scripts | Enables scripts |
allow-top-navigation | Allows links that target the top-level browsing contexts |
allow-same-origin | Allows content in the iframe to be treated as though it originated from the same location as the rest of the document |