doxy doxy - 2 months ago 10
jQuery Question

insert local javasscript into iframe html

I am trying to put some HTML code into iframe to present data. Everythink works fine, but when I want to put any java script in an iframe there is no result. It seems that iframe cannot see any local javascript.

Here is a code:

<html>
<head>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="testJSON.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<p id="demo"></p>
<script src="names.js"></script>
<script type="text/javascript">
$("#frame").attr(
"src", "data:text/html;charset=utf-8," +
"<html><head>"+
"<script src='jquery.min.js'><"+"/script>"+
"<script src='testJSON.js'><"+"/script></head>"+
"<body><p id='demo'></p>"+
"<script src='name.js'><"+"/script>"+
"<h1>Test</h1>"+
"</body></html>"
);
</script>
</body>
</html>


testJSON.js:

var dane = '{ "names" : [' +
'{ "firstName":"Ana" , "lastName":"Doe" },' +
'{ "firstName":"Bill" , "lastName":"Smith" },' +
'{ "firstName":"Dory" , "lastName":"Jones" } ]}';


names.js:

var nameID =function() {
return 2;
};

obj = JSON.parse(dane);
document.getElementById("demo").innerHTML =
obj.names[nameID()].firstName + " " + obj.names[nameID()].lastName;


Has anyone have a solution to this problem?

Thank you

Answer

I assume DataURIs cannot contain external scripts for security reasons but I cannot find the duplicate SO post that confirms this. Anyway, document.write the html and script into the frame. That works

$("#frame")[0].document.write( // or contentDocument.write
        "<html><head>"+
        "<script src='jquery.min.js'><\/script>"+
        "<script src='testJSON.js'><\/script></head>"+ 
        "<body><p id='demo'></p>"+
        "<script src='name.js'><\/script>"+  
        "<h1>Test</h1>"+
        "</body></html>"
    );
$("#frame")[0].document.close();

you may need to fully qualify the URLs of the external files

Comments