[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 iframeprovides 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 iframethe 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 embeddedto 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  1. 分离页面逻辑, realize modularization and facilitate page construction;
  2. Scripts can be 不同域名isolated to increase website security;
  3. Achieve 局部刷新, reduce bandwidth and improve website performance;
  4. 解决加载缓慢Loading issues with local third-party content such as icons and advertisements;
  5. Ability to load scripts in parallel;
  6. 方便管理, 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;
  7. iframe can 原封不动display embedded web pages.

3. Disadvantages of iframe:

  1. 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 crawl iframe;
  2. iframeThe loaded content cannot be traced and it is difficult to provide detailed log records;
  3. Security issues such as data transfer between parent and child pages are prone to occur, and there are 点击劫持risks of attacks;
  4. iframeIt will increase the number of requests and size of the page and reduce the page speed.
  5. It will generate a lot of pages and is not easy to manage.
  6. It will increase server httprequests and is not advisable for large URLs.
  7. loadEvents that will block the parent page
  8. 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:

  1. It is necessary to reduce the use and avoid embedding too much content, which will affect the loading speed of web pages;
  2. Set the width and height of the iframe to avoid confusing page layout;
  3. Dynamically configure iframe attributes as needed srcto avoid security issues;
  4. Cooperate CSSwith and JavaScriptto implement iframe style and event handling needs.

5. Application scenarios of iframe:

  1. Load third-party application content such as web maps;
  2. You can load same-origin or cross-origin pages through iframes to achieve modularization of the website.
  3. Embedding content from another domain name can usually be used for social media embedding, online video playback, etc.
  4. It can be used to load JavaScript applications, enable sandbox mode, and improve page maintainability.
  5. 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 page XSS攻击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;

  • widthand height: specify the width and height of the iframe frame;

  • namewindow.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 to scrolling = "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;

  • referrerpolicyreferer: 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 srcand width/heightmust 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 srcattributes 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 idthe 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.parentproperties 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 myFramethe 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. ajaxThe 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 reloadto obtain, and you can also 添加 iframeuse and 删除 iframeto 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 XHRand hard callback.

4. Adaptive iframe-ad embedding

Advertisements usually have nothing to do with the original text. If divthey 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 windowfully 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 clickpriority . 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.topto 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-OptionsIt 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 page
  • SAMEORIGIN: The address of the iframe page can only be a page under the same origin domain name
  • ALLOW-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-OptionsIn 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

sandboxIt is used to set a sandbox model for a specified iframe to limit more permissions of the iframe.
The sandbox is h5a new attribute of and IE10+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:

  • scriptScript cannot be executed
  • Unable to send ajaxrequest
  • Cannot use local storage, localStoragei.e. cookieetc.
  • New pop-ups cannot be created andwindow
  • Can't send表单
  • Cannot load additional plug-ins such as flashetc.

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 sandboxadd 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.

iframeThe creation of is slower than the creation of other elements including scriptsand . 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 ( )cssDOM1-2 个数量级onloadconnection pool

2. Block page loading

onloadIt 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 Safariand Chrome, JavaScript 动态设置 iframe 的 SRCthis blocking situation can be avoided by

3. The only connection pool

The browser can only open a small number of connections to webthe server. Older browsers, including Internet Explorer 6 & 7and , 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 .hostnameSafari 3+Opera 9+Chrome 1+IE 8Firefox 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 iframetechnology. Here are some relevant suggestions for your reference:

  • If you need to load content within the same site through an iframe, you can use Ajaxinstead.
  • 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, SVGdynamic effects or the use of WebGLiframe 图形渲染, 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.

Guess you like

Origin blog.csdn.net/weixin_55846296/article/details/131107784