Showing posts with label iframe. Show all posts
Showing posts with label iframe. Show all posts

Monday, October 30, 2017

How to hide iFrame

Sometimes we want to hide iframe from UI for different purposes like preload, download file, toggle effect etc. There are couple of ways to hide iFrame.
  • display:none
  • visibility:hidden
  • set height or width to zero
  • set position to offscreen
Here are explanations:
  • I don't suggest use display:none because some browsers like Firefox will skip rendering the iframe into DOM, then all logics/codes will not get executed
  • visibility:hidden will hide the iframe but will occupy the space
  • Set height and width to zero might also need set border to zero using frameBorder
  • Move iframe offscreen is an option I prefer using some class like below
             .offscreen {
                  position: absolute;
                  left: -5000px;
             }

Wednesday, February 27, 2013

Frame busting

More and more websites don't want them to be iframed in other websites, so they added frame busting setting or codes to their websites. Our web clipper can clip website URLs as a bookmark, so we need to deal with this frame busting thing - which is called anti-frame-busting or preventing frame busting.

Three ways if you don't want your website iframed in other websites:
1. X-Frame-Options: deny
In http header, and implemented by most browsers. iOS UIWebView seems to have not implemented this as of writing.

2. Traditional Javascript code
if (top != self) { top.location.replace(self.location.href); }

3. Javascript to show/hide body due to clickjack security concern
<body style="display:none" ...>
try {
  if (top.location.hostname != self.location.hostname)
    throw 1;
  document.body.style.display = 'block';
} catch (e) {
  // possible clickjack attack, leave content hidden
}

Then how to prevent frame busting?
Check out http://stackoverflow.com/questions/958997/frame-buster-buster-buster-code-needed for the discussions.

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.

Wednesday, September 12, 2012

postMessage Sample Codes

Cross-document messaging has 2 parts: sender and receivers. Sender can be parent window or child window,  and reciever can be child window and parent window. (sibling windows should also work, for browser tab or windows, need further research.) Here we only talk about the main window includes one iframe case for cross-document (cross-domain) messaging.

Sender (main window):
    var win = document.getElementById("iframe").contentWindow;
    win.postMessage(
            'the-sample-message',
            "http://www.target-origin.com"
    );


Sender (iframe window):
    parent.postMessage(msg, 'http://www.target-origin');

Receiver (onmessage event):
    window.onmessage = function(e){
        if ( e.origin !== "http://www.origin.com" ) {
            return;
        }
        // parse and validate e.data

        // processing e.data
    };

Receiver (customized event handler):
     var handleMessage = function(e) {
         if ( e.origin !== "http://www.origin.com" ) {
            return;
         }     

        // parse and validate e.data
        // processing e.data
    };

    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
    }


References
http://www.w3.org/TR/webmessaging/#web-messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
http://html5demos.com/postmessage2

addEvent utility function (from html5demos.com, good for reference)
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();



Tuesday, September 11, 2012

iframe Communication

iFrame is used on web page to mashup content from same or different domains, same domain looks straightforward, but same-origin-policy prevents direct communication between iframe(s) or parent window if the origins are different.

Same domain:

1. child iframe calls parent window JS function:
window.parent.functionName()

2. parent window calls iframe JS function:
document.getElementById('frameName').contentWindow.functionName()
Other alternatives for above JS code 
window.frames['frameName'].contentWindow.functionName();

var el = document.getElementById('frameName');
if(el.contentWindow) {
    el.contentWindow.functionName();
}
else if(el.contentDocument) {
    //el.contentDocument.functionName();
    el.contentDocument.defaultView.functionName();
}


Cross domain:
HTML5 Web Messaging http://dev.w3.org/html5/postmsg/#web-messaging defines cross document messaging to address this issue, and as of writing, it is supported in most browsers (except for IE7 and below) for iFrame-to-parent-window communication (IE has not implemented cross window/tab messaging yet). The standard API is window.postMessage(message, targetOrigin [,transfer]).

However if we need support old browsers for cross domain messaging, we need look at other hacks or solutions.
  1. Hashchange of iframe or parent window. For instance, parent window change iframe window's fragment (hashchange), and iframe polling the change (or onhashchange event) to get passed fragment identifier
  2. hidden proxy iframe, hashchange based
  3. hidden proxy iframe, resize event based (see https://github.com/ternarylabs/porthole/)
  4. Flash (some library uses flash fallback)
Libraries using postMessage with fallbacks
Client to server cross domain:
  1. proxy server
  2. JSONP
  3. CORS (Cross origin resource sharing)
Reference
http://softwareas.com/cross-domain-communication-with-iframes
http://stackoverflow.com/questions/6309674/wrapping-postmessage-in-jquery