0

I want to call a function in Iframe from parent window . as

var iframe = document.getElementById("myframe");
if (iframe) {
   var iframeContent = (iframe.contentWindow || iframe.contentDocument);

   iframeContent.targetFunction();
}

but it doesn't work .

Since the content of Iframe is added dynamically (All contents are added in iframe on demand even js file);

I had followed this

Invoking JavaScript code in an iframe from the parent page

There is any way to solve this problem ?

Community
  • 1
  • 1
  • A fiddle would be nice! – Brunis Aug 23 '14 at 10:42
  • @Brunis unable to create fiddle . – john abrahm Aug 23 '14 at 11:14
  • Before trying my answer. Try calling the function directly by using `parent.functionName()` .If it doesn't work go for my answer – Khaleel Aug 23 '14 at 14:27
  • @Brunis the question is and should be answerable without a fiddle. They are not required in questions. – Adjit Aug 23 '14 at 14:34
  • 1
    @Adjit that's true, but it's nice to have some example code to work from, which also shows he made an effort. This is not a "do this assignment for me" website. – Brunis Aug 23 '14 at 14:45
  • @Brunis I agree, however with this question you don't need a Fiddle, and the OP did not say "do this assignment for me" rather the OP showed their attempt and asked how to fix it. – Adjit Aug 23 '14 at 15:04
  • @Khaleel You are providing answer for reverse of question i.e. you are providing solution for calling a function in parent from Iframe .So please read question carefully . – john abrahm Aug 24 '14 at 06:12
  • @Brunis I was unable to set fiddle , due to document.write() and it's not allowed in fiddle .Iframe should contain , so document.write() is required . – john abrahm Aug 24 '14 at 06:15
  • @johnabrahm Add an empty.html file with a basic html5 template and use that as the iframe source. Then fill in the blanks from framing document. If it's your document/content, it IS possible to call functions on it and manipulate data. That's how most web based rich text editors work, eg. CKEditor. – Brunis Aug 24 '14 at 10:18

1 Answers1

0

There is a concept called postmessage in html

Try this below codes in corresponding scripts

in Parent

if (window.addEventListener) {
    window.addEventListener ("message", receive, false);        
}
else {
    if (window.attachEvent) {
        window.attachEvent("onmessage",receive, false);
    }
}

function receive(event){
    var data = event.data;
    if(typeof(window[data.func]) == "function"){
        window[data.func].call(null, data.params[0]);
    }
}

function alertMyMessage(msg){

    alert(msg);
}

in iFrame

function send(){
    window.parent.window.postMessage(
        {'func':'alertMyMessage','params':['Thanks for Helping me']},
        'http://www.my-website.com'
    );
}

refered: https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

Hope it helps

Khaleel
  • 1,212
  • 2
  • 16
  • 34