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');Inject Content into a new IFrame introduces 3 different ways to add concent to iframe
iframe.width = '100%';
iframe.height = '100%';
iframe.src = '{url to same origin resource or different web site}';
$('#container_div').append(iframe);
- Change the src attribute to an external document URL
- Use the DOM’s open(), write(), close() API to inject content
- Use the javascript: URI scheme
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