Friday, 23 August 2013

Cross domain form from iframe. Not working for some sites on IE

Cross domain form from iframe. Not working for some sites on IE

I have a bookmarklet that needs to submit some information to my website.
It must be able to run from all sites.
The below code has worked with all http sites that I have tried on Chrome
and Firefox. It does not, however, always work when I use it on IE. When
it fails, the form is not submitted. It is constant with regards to what
sites that it will and will not work with, although I do not know why.
When it fails, it's because this line fails to get iframeDoc.
var iframeDoc = i.contentDocument || i.contentWindow.document;
Here is a site where it does NOT work on IE:
http://www.bonappetit.com/recipe/double-banana-cake
Here is a site where it DOES work on IE:
http://www.bbcgoodfood.com/recipes/3256/moroccan-lamb-with-apricots-almonds-and-mint
Working means that the form is submitted.
How can I get this working?
// create iframe
var i=document.createElement('iframe');
// create form
var frm = document.createElement('form');
frm.method = "POST";
frm.action = "http://www.google.com";
frm.setAttribute('id', 'my_id');
// create script to submit form
var s = document.createElement('script');
s.innerHTML = 'document.getElementById("my_id").submit();';
// attach iframe to DOM
document.body.appendChild(i);
// attach form and script to iframe.
var intervalID = setInterval( function(){
// has to be in interval time due to IE since it fails the first
several times
try{
var iframeDoc = i.contentDocument || i.contentWindow.document;
clearInterval(intervalID);
attach_form_and_script();
alert("success!");
} catch(e){
}
}, 10 );
function attach_form_and_script(){
var iframeDoc = i.contentDocument || i.contentWindow.document;
iframeBody = iframeDoc.body;
iframeBody.appendChild(frm);
iframeBody.appendChild(s); // form is submitted
}

No comments:

Post a Comment