Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
               var iframe = $('<iframe></iframe>').attr({id:'iframe', width:'200',height:'200', border:'1'});
                $(document.body).append(iframe);
                $('#iframe').attr({src:'doc-iframe.php'});

                $('#iframe').load(function(){

                    $('<div></div>', this.contentWindow.document).append(function(){
                        $(this).append('<form name="test" id="test"><input name="name" value="Serban"><input type="submit"></form> <sc'+'ript>console.log(window); document.test.submit();</sc'+'ript>');
                    });

                });

The code above is executed on the page http://test.local/doc.html It tries to load some content into:

<iframe id="iframe" src="doc-iframe.php"></iframe>

The problem is that document.test.submit() is not executed inside the context of #iframe and document points to doc.html instead of doc-iframe.php.

How can i execute this code inside the context of #iframe?

Consider that the HTML code inside append() is the result from an html AJAX response that i cannot control.

share|improve this question

2 Answers

when you are working with an iFrame, with jQuery, you should always reference it like this:

$(this).contents().append(...)

I don't know if this helps, but your question is not very clear...

share|improve this answer
In side append you have 'document.form1.submit()' and this triggers document.form1 is undefined, because the context is the actual page not the iframe. This is my problem. – serbanghita Jan 31 '12 at 15:52
so, if the $(this) refers to the page, try $(this).find('#iframe').contents().append(...) – André Alçada Padez Jan 31 '12 at 15:54
Try to run the code replacing doc-iframe.php with an empty html file. You'll see the error. I tried every suggested solution, but it still doesn't work. – serbanghita Jan 31 '12 at 19:39

Use the context selector to specify the iframe as the target:

document.title = $("form#test", frames[0].document).submit();

Use an equality check to identify the context node:

console.assert($(this).get(0) === $(frames[0]).get(0), "not the iframe", $(this).get(0) );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.