[HTML] Master iframe in depth: Understand its technical principles, advantages and disadvantages, best application scenarios and practical guide
Foreword:
In web application development, it is a common requirement to include frameworks for other web pages. The HTML tag iframe
provides a container that can be used to embed other pages, and it comes with some useful features, such as resizing, scrolling, etc.
This article will provide an in-depth introduction to iframe
the technical principles, advantages and disadvantages, best application scenarios and practical guidelines, hoping to help you better use iframes and improve the efficiency of web application development.
1. Brief introduction and principles:
<iframe>
The (inline frame) element is a common HTML element used to embed an HTML document within another HTML document. The actual effect is to embed one document into another document, and the user can see and interact with the child document while browsing the parent document normally in the browser.
<iframe>
The loaded document is called inline frame content (IFC). The source of this document can be a server from the same domain, or it can be content from another domain. In the latter case (i.e., cross-domain access), due to the browser's same-origin policy, postMessage()
methods such as etc. can be used to complete communication between parent and child windows.
The principle is to use an inline frame and add it embedded
to the host document. The size, URL and other options of the inline frame are determined by the parent page. The content in the inline frame is loaded, parsed and rendered independently of the parent page.
1. The main features of iframe:
-
Realize nesting and embedding of web pages : iframe can embed another web page in one web page, thereby realizing the collaborative and simultaneous display of multiple web pages.
-
Implement partial refresh of the page : Since the content in the iframe can be loaded and rendered independently, it can be used to implement dynamic partial updates instead of refreshing the entire page.
-
Realize the segmentation of web pages : Through iframe, web pages can be split and divided into different modules, thereby making the web page functions clearer and easier to maintain.
-
Display of content from different sources : Since iframe can embed content from different sources in the same page, it can be used to display content from third-party platforms or applications, such as third-party videos, news, advertisements, etc.
2. Advantages of iframe:
分离页面逻辑
, realize modularization and facilitate page construction;- Scripts can be
不同域名
isolated to increase website security; - Achieve
局部刷新
, reduce bandwidth and improve website performance; 解决加载缓慢
Loading issues with local third-party content such as icons and advertisements;- Ability to load scripts in parallel;
方便管理
, if there are multiple pages that need to use the content of the iframe, then you only need to modify the content of the iframe to achieve unified management;- iframe can
原封不动
display embedded web pages.
3. Disadvantages of iframe:
- It is not conducive to search engine optimization, that is
SEO
, it is not conducive to the content that is difficult for search engines to crawliframe
; iframe
The loaded content cannot be traced and it is difficult to provide detailed log records;- Security issues such as data transfer between parent and child pages are prone to occur, and there are
点击劫持
risks of attacks; iframe
It will increase the number of requests and size of the page and reduce the page speed.- It will generate a lot of pages and is not easy to manage.
- It will increase server
http
requests and is not advisable for large URLs. load
Events that will block the parent page- The iframe and the main page share the connection pool, and the browser has restrictions on connections in the same domain, so it will affect the page.
并行加载
That is to say, the number of requests for the subdocument and the parent document will be calculated together.
4. Solution:
To avoid the above shortcomings, the following measures need to be taken:
- It is necessary to reduce the use and avoid embedding too much content, which will affect the loading speed of web pages;
- Set the width and height of the iframe to avoid confusing page layout;
- Dynamically configure iframe attributes as needed
src
to avoid security issues; - Cooperate
CSS
with andJavaScript
to implement iframe style and event handling needs.
5. Application scenarios of iframe:
- Load third-party application content such as web maps;
- You can load same-origin or cross-origin pages through iframes to achieve modularization of the website.
- Embedding content from another domain name can usually be used for social media embedding, online video playback, etc.
- It can be used to load JavaScript applications, enable sandbox mode, and improve page maintainability.
- Embed interactive components such as Facebook social media plug-ins, custom maps, online forms, live chat functionality, and more.
It should be noted that since iframes can embed
不同源
content from within the same page, there are certain security risks. Therefore, you need to pay attention to some security issues when using iframes安全问题
, such as pageXSS攻击
security, etc.点击劫持
At the same time, when implementing complex page embedding and nesting, you also need to pay attention页面的性能
to加载速度
issues such as
2. Use of iframe
1. Common attributes:
Here are <iframe>
some common properties of elements:
-
src
: Specify the nested page URL address; -
width
andheight
: specify the width and height of the iframe frame; -
name
window.frames[name]
: Specify the name of the iframe and access the iframe in js ; -
scrolling
: Determine whether to display the scroll bar. You can use it toscrolling = "auto"
automatically decide whether to display the scroll bar, or set it to "yes" and "no" to specify whether to always display or hide the scroll bar; -
frameborder
: Specify the border of the display component. You can use the values "0", "1" and "no", "yes" to specify whether to display the border; -
sandbox
: Specify which functions can be used when a web page is embedded in an iframe, specify the permissions and security of resources contained in the iframe, etc.; -
allowfullscreen
: Specify whether to allow video playback in full-screen mode; -
referrerpolicy
referer
: Specifies when to set the header in the assertion of an HTTP request . -
allowpaymentrequest
: Allow pages in iframes to request permissions from the user; -
allowpopup
: Allow new windows to pop up when clicking links in inline frames; -
allowtransparency
: Allows iframes to specify transparency.
Among these attributes, basic attributes such as src
and width/height
must be specified. Other properties depend on the specific application scenario.
2. Use (operation method):
An iframe (inline frame) is an HTML element used to embed an HTML document within another HTML document. The following is an introduction to common usage scenarios and related operation methods of iframe:
1. Simple use of iframe
In HTML pages, you can use <iframe>
elements to create a nested page. When using <iframe>
the element, you need to set src
attributes to specify the URL of the embedded page. For example:
<iframe src="https://www.example.com"></iframe>
This code will embed page content from https://www.example.com in the current page.
2. Get iframe element
To get the iframe element, you can use the method in JavaScript document.getElementById()
and pass in id
the attribute value of the iframe as a parameter. For example:
<iframe id="myFrame" src="https://www.example.com"></iframe>
var iframe = document.getElementById('myFrame');
This code will get an iframe element with the specified id "myFrame".
3. Get iframe element value
To get the value of the content inside the iframe element, you can use attributes in JavaScript contentDocument
. For example:
<iframe id="myFrame" src="https://www.example.com"></iframe>
var iframe = document.getElementById('myFrame');
var iframeContent = iframe.contentDocument.body.innerHTML;
The above code will obtain the internal HTML content of an iframe element with the specified id "myFrame".
4. iframe obtains information from the parent page
In an iframe, you can use window.parent
properties to get the parent window object in which it is located. Through this object, mutual communication between parent and child pages can be achieved. For example:
In the parent page:
<iframe id="myFrame" src="https://www.example.com"></iframe>
function getTextFromIframe() {
var iframe = document.getElementById('myFrame');
var iframeContent = iframe.contentDocument.body.innerHTML;
iframe.contentWindow.postMessage({
message: 'getIframeContent' }, '*');
}
window.addEventListener('message', function(event) {
if (event.data.message === 'getIframeContent') {
var iframeContent = document.getElementById('myFrame').contentDocument.body.innerHTML;
event.source.postMessage({
message: 'iframeContent', content: iframeContent }, '*');
}
});
In an iframe:
window.addEventListener('message', function(event) {
if (event.data.message === 'getIframeContent') {
var iframeContent = document.getElementById('myFrame').contentDocument.body.innerHTML
event.source.postMessage({
message: 'iframeContent', content: iframeContent }, '*')
}
})
The above code will obtain myFrame
the internal HTML content of an iframe element with the specified id " ", and window.postMessage()
send the content to the parent window through the method. In the parent window, by adding an event listener, you can get the content returned by the iframe.
3. Long polling of iframe
Long polling is when the original function is executed again.
ajax
The same is true for using iframe here. Create the iframe asynchronously and then reloadreadyState = 4
var iframeCon = docuemnt.querySelector('#container'),
text; //传递的信息
var iframe = document.createElement('iframe'),
iframe.id = "frame",
iframe.style = "display:none;",
iframe.name = "polling",
iframe.src = "target.html";
iframeCon.appendChild(iframe);
iframe.onload = function () {
var iloc = iframe.contentWindow.location,
idoc = iframe.contentDocument;
setTimeout(function () {
text = idoc.getElementsByTagName('body')[0].textContent;
console.log(text);
iloc.reload(); // 刷新页面,再次获取信息,并且会触发 onload 函数
}, 2000);
}
The same goes for using iframe here. Create the iframe asynchronously and then reload it. In this way, the effect of ajax long polling can be achieved.
Of course, here we only use reload
to obtain, and you can also 添加 iframe
use and 删除 iframe
to send information. These are all applied according to specific scenarios.
In addition, it can also be implemented in an iframe 异步加载 js 文件
. However, the iframe and the homepage share a connection pool, and are now basically banned by XHR
and hard callback
.
4. Adaptive iframe-ad embedding
Advertisements usually have nothing to do with the original text. If div
they are nested directly under a certain , it will cause problems 网页布局的紊乱
, and additional css and js files will need to be introduced, which greatly reduces the security of the web page . All these disadvantages can be solved using iframe.
An iframe can be understood as one 沙盒
, and the content inside can be top window
fully controlled. Moreover, the css style of the homepage will not invade the style inside the iframe.
By default, iframe will have its own scroll bar and will not be full screen. If you want to adapt the iframe:
1. Remove the scroll bar
<iframe src="./iframe1.html" id="iframe1" scrolling="no"></iframe>
2. Set the height of iframe to the height of body
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
iframe.height = idoc.body.offsetHeight;
5. Security of iframe
1. Anti-nested web pages
iframe has click
priority . When someone clicks on the fake homepage, if he clicks on the iframe, he will be operating the page of the iframe by default. Therefore, phishing websites use this technology to induce users to click.
In order to prevent the website from being phished, you can use window.top
to prevent the web page from being iframed, which means that your web page cannot be nested in any web page:
// iframe2.html
if (window != window.top) {
window.top.location.href = correctURL;
}
2、 X-Frame-Options
X-Frame-Options
It is a corresponding header, which mainly describes the iframe permissions of the server's web resources . There are 3 options:
DENY
: The current page cannot be nested in an iframe , even if it is nested in a page with the same domain name, nor is it allowed to have nested iframes in a web pageSAMEORIGIN
: The address of the iframe page can only be a page under the same origin domain nameALLOW-FROM
: Can be loaded in the iframe of the specified origin url
Simple example:
X-Frame-Options: DENY
拒绝任何iframe的嵌套请求
X-Frame-Options: SAMEORIGIN
只允许同源请求,例如网页为 foo.com/123.php,則 foo.com 底下的所有网页可以嵌入此网页,但是 foo.com 以外的网页不能嵌入
X-Frame-Options: ALLOW-FROM http://s3131212.com
只允许指定网页的iframe请求,不过兼容性较差Chrome不支持
X-Frame-Options
In fact, it is to hand over the control of iframe by front-end js to the server for processing.
// js
if (window != window.top) {
window.top.location.href = window.location.href;
}
// 等价于
X-Frame-Options: DENY
// js
if (top.location.hostname != window.location.hostname) {
top.location.href = window.location.href;
}
// 等价于
X-Frame-Options: SAMEORIGIN
This attribute is a major restriction on the iframe of the page. However, there are more than one headers involved in the iframe. There is another one Content Security Policy
, and the iframe can also be restricted.
3、sandbox
sandbox
It is used to set a sandbox model for a specified iframe to limit more permissions of the iframe.
The sandbox ish5
a new attribute of andIE10+
is supported.
The way to enable it is to use the sandbox attribute :
<iframe sandbox src=”...”></iframe>
This will impose a series of restrictions on iframe pages:
script
Script cannot be executed- Unable to send
ajax
request - Cannot use local storage,
localStorage
i.e.cookie
etc. - New pop-ups cannot be created and
window
- Can't send
表单
- Cannot load additional plug-ins such as
flash
etc.
At the same time, you can relax some permissions. Make some simple settings in the sandbox:
<iframe sandbox=”allow-same-origin” src=”...”></iframe>
Commonly used configurations are:
Configuration | Effect |
---|---|
allow-forms | Allow form submission |
allow-scripts | Run execution script |
allow-same-origin | Allow requests from the same domain, such as ajax and storage |
allow-top-navigation | Allow iframe to dominate window.top for page jumps |
allow-popups | Allow new windows to pop up in iframes, such as window.open, target="_blank" |
allow-pointer-lock | The mouse can be locked in an iframe, mainly related to mouse locking |
You can sandbox
add permissions to allow it in .
<iframe sandbox=”allow-forms allow-same-origin allow-scripts” src=”...”></iframe>
This ensures the execution of js scripts, but prohibits the execution of javascript in iframes.top.location = self.location
6. Limitations of iframe
1. Creation is 1-2 orders of magnitude slower than ordinary DOM elements.
iframe
The creation of is slower than the creation of other elements including scripts
and . Pages using iframes generally do not contain too many iframes, so the time spent creating DOM nodes does not account for a large proportion. But it brings some other problems: events and connection pooling ( )css
DOM
1-2 个数量级
onload
connection pool
2. Block page loading
onload
It is very important to trigger window events in time . The onload event triggers to stop the browser's "busy" indicator, telling the user that the current web page has been loaded. When the onload event is delayed, it gives the user the feeling that the web page is very slow.
The onload event of window needs to be triggered after all iframes have been loaded (including the elements inside). In Safari
and Chrome
, JavaScript 动态设置 iframe 的 SRC
this blocking situation can be avoided by
3. The only connection pool
The browser can only open a small number of connections to web
the server. Older browsers, including Internet Explorer 6 & 7
and , can only open 2 connectionsFirefox 2
to a domain name ( ) at the same time . This number limit has been increased in newer versions of the browser. and can open 4 connections to a domain name at the same time , , and can open 6 at the same time .hostname
Safari 3+
Opera 9+
Chrome 1+
IE 8
Firefox 3
In most browsers, the main page and the iframes within it share these connections . This means that the iframe may use up all available connections while loading resources, thus 阻塞了主页面资源的加载
. This is of course good if the content in the iframe is more important than the content of the main page. But usually, the content in the iframe is not as important as the content of the main page. At this point it's not worth it to run out of available connections in the iframe. One solution is to dynamically set the iframe after the important elements on the main page are loadedsrc
.
4. Not conducive to SEO
Search engine crawlers cannot interpret iframes.
In addition, iframe itself is not a dynamic language, and styles and scripts need to be imported additionally. In summary, iframes should be used with caution.
7. Practical Guide to iframe
In actual development, we often need to use iframe
technology. Here are some relevant suggestions for your reference:
- If you need to load content within the same site through an iframe, you can use
Ajax
instead. - It is not recommended to use iframes for
搜索引擎
indexing because embedded page content cannot be crawled externally by content indexers. - If the embedded page belongs
第三方站点
, you need to pay attention to身份验证
other security issues. - For some specific application scenarios, such as display
Canvas
,SVG
dynamic effects or the use ofWebGL
iframe图形渲染
, iframe can be used.
Summarize
<iframe>
Elements have a wide range of usage scenarios. Its advantage is that it can embed a web page into another web page to achieve richer interaction and user experience; at the same time, using postMessage()
other methods, communication between parent and child windows can be achieved. But <iframe>
elements also have shortcomings, and there are some issues in cross-domain access and mobile device performance. In practical applications, it is necessary to determine whether to use it based on the specific situation <iframe>
and choose a solution reasonably.