1

I have a knowledge base for my work. I'm trying to get full html w/scripting setup within a iFrame instance.

Below is a Chrome expansion of my setup. When I click the button in my div/iframe, I get a Uncaught ReferenceError: test is not defined error.

Thoughts?

enter image description here

3 Answers 3

1

http://bytes.com/topic/javascript/answers/153274-script-iframe-can-not-call-functions-defined-parent-document

Per link: Functions are not properties of the document, but of the window. Try parent.foo(); or top.foo();

<button onclick='parent.test();'>test</button> works now... top.test() works too, BUT, I'd like a way to normalize this. Its not very intuitive.

Is there a way to NOT have to prefix top. or parent.?

Sign up to request clarification or add additional context in comments.

1 Comment

@Huangism Test() is defined in the iFrame as the OP screenshot suggests. Now, I'm just trying to figure out why i need to use a prefix for the function wot work... weird.
0

Make sure the jQuery library is being called before any other script inside your <head> section.

Most of the times I get this error, I just change the order the scripts being called on the page (always under jQuery) and it solves the problem.

4 Comments

The OP is not using jQuery.
I do use jQuery, but that should be outside the scope of this simple example.
I mentioned jQuery because I get this exact same error very often, and simply reordering the scritps libraries solves the problem. Even when the error doesn't use jQuery, it can conflict.
I got it to work as noted in the above comment, but I want to have the need for prefixing top or parent for all js calls.
0

This is a late answer, but I'll share my solution.

I needed an iframe as a preview container. So parent.something would be a hassle.

This seems to work:

<iframe id='iframe' sandbox="allow-same-origin allow-scripts"></iframe>

And populate it with this (example using jquery):

$(function() {

    let $iframe = $('#iframe');
    $iframe.ready(function() {

       let ifhead = `
       <meta charset="UTF-8"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"><\/script>`;
       let ifbody = `<h1>My Body</h1>`;
       let ifscript = `$(function() { $('h1').css('color', 'blue')})`;
       let html = `<html><head>${ifhead}</head><body>${ifbody}<script>${ifscript}<\/script></body></html>`; 


       document.getElementById("iframe").contentWindow.document.open();
       document.getElementById("iframe").contentWindow.document.write(html);
       document.getElementById("iframe").contentWindow.document.close();

    });

});

Now the iframe acts as a stand-alone page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.