In some browsers, using iframe.onload = may not be optimal (might not work in some, may cause memory drain in others, and/or both). And, just in case the code does execute synchronously, the load function should be assigned before the request is made (src attribute change). Further, iframe.contentDocument is not valid in all browsers (there's another way around that than what I feature below, treating the iframe as a window - it's simpler but excludes using the getElementById() method to get a reference to the iframe). That all said, you can do whatever you like. My current version of the code looks like so:
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cross Origin Security Error</title>
</head>
<body>
<iframe src="http://www.example.com/" id="iframe"></iframe>
<input type="button" value="Color it!" id="button">
<script>
var addEvent = (function(){return window.addEventListener? function(el, ev, f){
el.addEventListener(ev, f, false);
}:window.attachEvent? function(el, ev, f){
el.attachEvent('on' + ev, f);
}:function(){return;};
})(), removeEvent = (function(){return window.addEventListener? function(el, ev, f){
el.removeEventListener(ev, f, false);
}:window.attachEvent? function(el, ev, f){
el.detachEvent('on' + ev, f);
}:function(){return;};
})(), iframe = document.getElementById('iframe'), button = document.getElementById('button'), iDoc;
function colorbg(){
if(!iDoc){
iDoc = (function(){
return iframe.contentDocument? function(){return iframe.contentDocument;} :
iframe.contentWindow? function(){return iframe.contentWindow;} : null;
})();
}
if (iDoc && iDoc().body){
iDoc().body.style.background = 'red';
}
removeEvent(iframe, 'load', colorbg);
}
addEvent(button, 'click', function () {
addEvent(iframe, 'load', colorbg);
iframe.src = 'linked-frame.html';
});
</script>
</body>
</html>
Even at that, it might not work out well in all browsers. I think older Opera was weird about the reference to the document in the iframe.
Bookmarks