kenyu73
kenyu73

Reputation: 681

Getting a not defined error with scripts embedded in an iFrame

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

Upvotes: 1

Views: 3783

Answers (3)

user3791775
user3791775

Reputation: 471

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.

Upvotes: 0

kenyu73
kenyu73

Reputation: 681

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.?

Upvotes: 1

mah2602
mah2602

Reputation: 98

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.

Upvotes: 0

Related Questions