Tuesday, October 2, 2012

Inline frame

<iframe> element was first introduced by Microsoft IE in 1997, standardized in HTML 4.0 Transitional, and is allowed in HTML 5. There is still some use cases to use iframe, like website ad, embed multimedia and cross domain web content sharing. Its other similar elements like <frameset>, <frame>, <noframes> are obsolete in HTML 5.

Recently I encountered one use case which might be a reason to use iframe in regard to some cons like browser support, firewall blocking, SEO concerns and so on. These inline frames allow the designer to put frames of other websites in the middle of a current website without a lot of coding efforts. Here is one code example to create iframe and append to DOM.
var iframe = document.createElement('iframe');
iframe.width = '100%';
iframe.height = '100%';
iframe.src = '{url to same origin resource or different web site}';
$('#container_div').append(iframe);
Inject Content into a new IFrame introduces 3 different ways to add concent to iframe
  1. Change the src attribute to an external document URL
  2. Use the DOM’s open(), write(), close() API to inject content
  3. Use the javascript: URI scheme
iframe.src = 'the url to my content';

iframe.contentWindow.document.open('text/html', 'replace');
iframe.contentWindow.document.write(myContent);
iframe.contentWindow.document.close();

iframe.contentWindow.contents = myContent;
iframe.src = 'javascript:window["contents"]';

In most cases, iframe works well to load other web site content, but sometimes browser (Chrome in my test) will throw error "Refused to display document because display forbidden by X-Frame-Options." This happens when there is X-Frame-Options HTTP header sent by target website and prevents displaying that page in an iframe. For more info about this header, check out MDN: The_X-FRAME-OPTIONS_response_header. Google, Yahoo etc set this header either to DENY or SAMEORIGIN to prevent being inlined. In this case, need present some friendly message to website visitors.

No comments:

Post a Comment