not able to access iframe contents using jquery or javascript


I was trying to manipulate HTML inside iframe using jquery-javascript, I am trying something like this

$(document).ready(function(){
    $('#Selector', frames['nameOfMyIframe'].document).functionStuff();
});

But I am not able to get the contents of an iframe, I get the Undefined error if iFrame is not loaded completely and when it loads I am getting permission error

How can I resolve this issue and access iframe contents using jquery?


Asked by:- neena
3
: 5758 At:- 7/26/2017 7:30:39 AM
jQuery javascript iframe-contents







3 Answers
profileImage Answered by:- manish

Your issue of not able to access iframe elements using jQuery or javascript is related to same origin policy, that's why you are getting the permission error.

If the <iframe> is from the same domain, the elements are accessible using jQuery like

$("#iFrame").contents().find("#DivID").AnyFunction();

Or you can try this method which triggers after loading of iFrame gets complete

$(document).ready(function(){
//executes once the iframe has finished loading
 $("#iframeID").ready(function () { 
       $('#Selector', frames['nameOfMyIframe'].document).functionStuff();
    });
    
});

Above solution will resolve your loading issue, but it will not resolve cross-domain issue(permission error)

3
At:- 7/26/2017 8:34:32 AM Updated at:- 12/24/2022 7:15:17 AM
I tried the first solution and it works for me 0
By : neena - at :- 9/8/2017 7:53:35 AM


profileImage Answered by:- vikas_jk

You can try this code also

$(document).ready(function(){
    $('#IfOfFrame').load(function(){
        $('#IfOfFrame').contents().find('body').html('Your new HTML Here');
    });
});
1
At:- 8/30/2017 7:58:22 AM


profileImage Answered by:- jon

Try using 

var $iframe = $("#iframeID").contents();
$iframe.find('selector');

But your iframe content must be from same origin otherwise you will get error permission denied type error.

0
At:- 12/24/2022 2:34:06 PM Updated at:- 12/24/2022 2:34:19 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use