Understanding the use of iframe

1. What is an iframe.

frame is used to display the page within the page, using iframe will create an inline frame (that is, an inline frame) that contains another document

<iframe src="URL"></iframe>

Second, the common attributes of iframe

1、width

Define the width of the iframe

2、height

Define the height of the iframe

3、name

Specifies the name of the iframe

4、frame border

Specifies whether to display the border, the value is 0 (not displayed) and 1 (displayed)

5、scrolling

Specify whether to display the scroll bar in the iframe, the value is yes, no, auto

6、src

Set the address of the iframe (page/image)

7、srcdoc

Used to replace the content in html and body in iframe (IE does not support)

8、sandbox

Restrict the content of the iframe, the value is

  • allow-forms
  • allow-same-origin
  • allow-scripts
  • allow-top-navigation

Support IE10+

3. Get the content in the iframe

1. Get the iframe

var iframe = document.getElementById("iframe1");

2. Get the window object of the iframe

  • via iframe.contentWindow
var iwindow = iframe.contentWindow;

  • The window object can also be obtained by window.frames['name']
var iwindow = window.frames["name"];

3. Get the document object of the iframe

  • Get the document object of the iframe
var idoc = iwindow.document;

Fourth, get the parent content in the iframe

  1. Get the upper-level window object
    Get the upper-level window object through window.parent (iframe can be used in multiple layers)

  2. Get the window object of the top-level container
    Get the window object (that is, the document when the page is opened) through window.top

  3. Return its own window object
    Return its own window object through window.self

5. Long polling of iframe

Long polling is to execute the original function again when the readyState of ajax = 4.

The same is true for using iframe here, create iframe asynchronously, and then reload.

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);
}

In this way, the effect of ajax long polling can be achieved.

Of course, here we only use reload to obtain, and we can also add iframe and delete iframe to send information, which are applied according to specific scenarios.

In addition, js files can be loaded asynchronously in the iframe, but the iframe and the home page share the connection pool, which is basically banned by XHR and hard callback now.

6. Responsive iframe - ad embedding

Advertisements usually have nothing to do with the original text. If they are nested directly under a certain div, the layout of the webpage will be disordered, and additional css and js files will need to be introduced, which greatly reduces the security of the webpage. All these disadvantages can be solved by using iframe.

The iframe can be understood as a sandbox, the content inside can be completely controlled by the top window, and 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 to iframe:

1. Remove the scroll bar

<iframe src="./iframe1.html" id="iframe1" scrolling="no"></iframe>
2、设置 iframe 的高为 body 的高
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
iframe.height = idoc.body.offsetHeight;

In addition, other decoration attributes can be added:

Attributes Effect
allowtransparency true or false whether to allow the iframe to be transparent, the default is false
allowfullscreen true or false whether to allow iframe full screen, the default is false

7. Security of iframe

1. Anti-nested web pages

The iframe enjoys the priority of click. When someone clicks on the fake homepage, if he clicks on the iframe, he will be operating the iframe page by default. Therefore, phishing websites use this technique to induce users to click.

In order to prevent the website from being phished, you can use window.top to prevent the webpage from being iframed, which means that your webpage cannot be nested in any webpage:

// iframe2.html
if (window != window.top) {
    
    
  window.top.location.href = correctURL;
}

2. X-Frame-Options

X-Frame-Options is a corresponding header, which mainly describes the iframe permission of the web resource of the server, and has 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, and nested iframes are not allowed in web pages
  • SAMEORIGIN: The address of the iframe page can only be a page under the same 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-Options is actually handing over the front-end js control over the iframe 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 header related to the iframe. There is also a Content Security Policy, which can also restrict the iframe

3. sandbox

sandbox is used to set a sandbox model for the specified iframe to limit more permissions of iframe
sandbox is a new attribute of h5, IE10+ supports
the enabling method is to use the sandbox attribute:


<iframe sandbox src=...></iframe>

This imposes a series of restrictions on the iframe page:

  • script script cannot be executed
  • Can't send ajax request
  • Cannot use local storage, i.e. localStorage, cookies, etc.
  • Cannot create new popups and windows
  • Can't send form
  • It is not possible to load additional plug-ins such as flash, etc.
    At the same time, the permissions can be relaxed a little. Make some simple settings in the sandbox
<iframe sandbox=”allow-same-origin” src=...></iframe>

Commonly used configuration items are:

configuration Effect
allow-forms Allow form submission
allow-scripts run script
allow-same-origin Allow same-domain requests, such as ajax, storage
allow-top-navigation Allow iframe to dominate window.top for page jump
allow-popups Allow new windows to pop up in iframe, such as window.open, target="_blank"
allow-pointer-lock The mouse can be locked in the iframe, mainly related to the mouse lock

You can add the permissions that are allowed in the sandbox.


<iframe sandbox=”allow-forms allow-same-origin allow-scripts” src=...></iframe>

This can ensure the execution of the js script, but prohibit the execution of javascript in the iframe top.location = self.location

8. Limitations of iframe

1. Creation is 1-2 orders of magnitude slower than normal DOM elements

The creation of iframe is 1-2 orders of magnitude slower than the creation of other DOM elements including scripts and css. The page using iframe generally does not contain too many iframes, so the time spent creating DOM nodes will not account for a large proportion. But it brings some other problems: onload event and connection pool (connection pool)

2. Block page load

It is very important to trigger the window's onload event in time. The onload event fires to stop the browser's "busy" indicator, telling the user that the current page has finished loading. When the onload event is delayed, it gives the user the impression that the page is very slow.

The window's onload event needs to be triggered after all iframes are loaded (including the elements inside). In Safari and Chrome, dynamically setting the SRC of the iframe through JavaScript can avoid this blocking situation

3. The only connection pool

The browser can only open a small number of connections to the web server. Older browsers, including Internet Explorer 6 & 7 and Firefox 2, can only open two connections to one domain name (hostname) at the same time. This number limit has been increased in newer versions of the browser. Safari 3+ and Opera 9+ can open 4 connections to a domain at the same time, Chrome 1+, IE 8 and Firefox 3 can open 6 connections at the same time.

In most browsers, the main page and the iframe within it share these links. This means that the iframe may use up all available connections while loading resources, blocking the main page resources from loading. This is of course fine if the content in the iframe is more important than the content of the main page. But usually, the content in the iframe is less important than the content of the main page. It's not worth using up the available connections in the iframe at this point. One solution is to dynamically set the SRC of the iframe after the important elements on the main page are loaded.

4. Bad for SEO

Search engine crawlers cannot interpret iframes.

In addition, iframe itself is not a dynamic language, and both styles and scripts need to be imported additionally. In summary, iframes should be used with caution.

Understanding the use of iframe

Reference article @Leophen

Guess you like

Origin blog.csdn.net/i_Satan/article/details/130242886