I have a file x.xhtml and another file main.html, in which I am using <iframe src=x.xhtml id=childframe>. Now what I want to do is, after the file is loaded, I want to get the source of the child frame, i.e x.xhtml, using JavaScript.
I tried the following code
function getChildInput() {
var iframe = document.getElementById('childFrame').contentWindow;
var childText = iframe.document.getElementById('childText');
alert(iframe.document.getElementsByTagName('html')[0].innerHTML);
}
but it didn't work for .xhtml. If I am using .html instead, it works fine.
Is this a problem with XHTML or is there any other way of getting the source from the child frame other than HTML?
Try alert(iframe.document.body.innerHTML);
or
var doc_iframe = document.getElementsByName("myFrame")[0].contentWindow.document;
HTH
Ivo Stoykov
Try using the documentElement property:
alert(iframe.document.documentElement.innerHTML);
Related
I have a javascript code which is connected to a htlm called "old.html". I do thing in there and then I have another html called "new.html" in which I want to add html elements in there.
I have this code in which I try to assign the div q1 to the variable myVar.
var printWindow = window.open("http://10.180.101.58:5500/new.html", 'Print');
var myVar = printWindow.document.getElementById('q1');
my html looks like this:
<body>
<form>
<div id="q1"></div>
</form>
<script src="DemoCode.js"></script>
</body>
These 2 files are in the same directory, but I think the problem is with the window.open()
I can't do document.getElementById() because I also have the "old.html" which let's say is the original html connected to my javascript and whenever I call document.getElementById() it gets elements from that one.
Does anyone know any way so that I can get elements from "new.html""?
I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.
There are two answers here:
If the window where the code doing this is on the same origin (http://10.180.101.58:5500),
you have to wait for the DOM to be loaded in the new window (for instance, using the DOMContentLoaded event) before you can access it.
If the window where the code doing this isn't on the same origin as the new window you're opening, then you can't access its DOM, since of course that would be a massive security hole.
Here's how you'd do it in case #1:
const printWindow = window.open("http://10.180.101.58:5500/new.html", "Print");
printWindow.addEventListener("DOMContentLoaded", () => {
const myVar = printWindow.document.getElementById("q1");
// ...use it here...
});
I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.
That doesn't in any way connect the windows (imagine all the windows that would be connected by jQuery or React loaded from a CDN!). All it does is load the code in that file into both windows.
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?
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.?
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.
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.
I have a function to grab a video title from a YouTube json callback, which works - however I'm having issues inserting the variable into an element.
Here is the feed I'm grabbing:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/2WNrx2jq184?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
The javascript function I'm using:
function youtubeFeedCallback(data) {
var info = data.entry.title.$t;
document.write(info);
}
This works fine, but I'd like to insert it into a div with the ID "box".
Usually I would use the following (and add it to the function - and remove the document.write):
var box = document.getElementById('box');
box.innerHTML = info;
I just cannot get this to work though. What would be the correct way to achieve what I'm trying to do? Thanks
http://jsfiddle.net/b3VYT/
Either make sure that the script is below the element or wrap your code in a document.ready callback so that it is not run until after the DOM is loaded.
http://jsfiddle.net/b3VYT/1
You need to make sure that the element that you are using is declared prior to your script executing:
<div id='test'></div>
<script>
function youtubeFeedCallback(data) {
document.getElementById('test').innerHTML = data.entry.title.$t;
}
</script>
Example
Edit: Just found out this is a chrome problem, the code works fine in firefox
I have an iframe on a webpage that shows a book formatted as html. I would like to insert some javascript within this iframe to make the book more dynamic (e.g. click on sentences, show animations etc). The iframe content is in the same domain as the parent page.
I can insert the javascript into the iframe but get an error calling a function in the inserted javascript. I've described the different bits of code below:
My parent page javascript is:
function iframeLoaded()
{
var iFrameID = document.getElementById('preview-iframe');
var jsLink = iFrameID.contentDocument.createElement("script");
jsLink.src="/tests/iframeAPI.js";
jsLink.type = 'text/javascript';
iFrameID.contentDocument.head.appendChild(jsLink);
iFrameID.contentWindow.initialiseApi()
}
and the html containing the iframe is:
<iframe id="preview-iframe" width="640" height="240" frameborder="0" src="./testpage.htm" onload="iframeLoaded()" scrolling="no"></iframe>
The contents of iframeAPI.js is:
window.initialiseApi = function() { alert("Hello world") }
Looking at the iFrame's html in the browser shows that the iFrameAPI.js tag is inserted ok into the iframe head, but I don't get the alert popup when the page is loaded. The error appears on the following line:
iFrameID.contentWindow.initialiseApi()
Uncaught TypeError: Object [object Window] has no method 'initialiseApi'
However I can run this line in the browser's javascript console and the alert popup works fine.
Any help would be much appreciated.
Thanks,
Brian
Edit: I've just tried with an onload event to make sure the page is loaded and I still have the problem:
My parent page javascript is now :
function iframeLoaded()
{
var iFrameID = document.getElementById('preview-iframe');
var jsLink = iFrameID.contentDocument.createElement("script");
jsLink.src="/tests/iframeAPI.js";
jsLink.type = 'text/javascript';
iFrameID.contentDocument.head.appendChild(jsLink);
jsLink.onLoad= iFrameLoaded();
}
function iFrameLoaded()
{
alert("Iframe loaded"); // Alert works ok
var iFrameID = document.getElementById('preview-iframe');
iFrameID.contentWindow.initialiseApi(); // Same error message on this line
}
It sounds like you are trying to use the function before the content has loaded.
try this instead:
var t = setTimeout(iFrameID.contentWindow.initialiseApi(),500);
This will wait half a second before trying the function which should give the page tiem to load. Delay times are given in milliseconds.
An even better approach is to try using Jquery and its ready() method but this requires the jquery library to be loaded as well. Its well worth it though in my opinion, see http://api.jquery.com/ready/.
You would try something like:
$("body",iFrameID.contentWindow.document).ready(iFrameID.contentWindow.initialiseApi())
You're executing it right away without giving the script a chance to load. Hook up an onload event to your script block and run your main function then.
Try, in the page included in the iFrame, accessing the main page by doing something like:
window.parent.xyz = something;
Where something is what you want exposed to the main page. Could be a function or an object of functions. Now in the main page you can just do:
something(); // or something.somefunction();
You could also send window references, I think, but I have not tried that.
The easiest way is to call the initialiseApi function in the iframeAPI.js itself as it will be called as soon as it's loaded. The iframeAPI.js could look like that:
function initialiseApi() {
alert("Hello world");
}
initialiseApi();
There is no callback or timeout needed.
In javascript, how can I set the innerHTML of an iframe? I mean: how to set, not get.
window["ifrm_name"].document.innerHTML= "<h1>Hi</h1>" does not work, and the same for other solutions.
Iframe and parent document are on the same domain.
I would need to set html of the whole document iframe, not its body.
I would need to avoid jquery solution.
A really simple example ...
<iframe id="fred" width="200" height="200"></iframe>
then the following Javascript is run, either inline, part of an event, etc ...
var s = document.getElementById('fred');
s.contentDocument.write("fred rules");
the "contentDocument" is the equivalent of the "document" you get in the main window, so you can make calls against this to set the body, head, any elements inside ... etc.
I've only tested this in IE8, Chrome and Firefox ... so you may want to test in IE6/7 if you have copies available.
In Firefox and Chrome (don't know about Opera), you can use the data: URI scheme.
<iframe src=".... data: URI data here ......">
JSFiddle example
Here is a tool to generate data:URI encoded data.
This does not work in IE:
For security reasons, data URIs are restricted to downloaded resources. Data URIs cannot be used for navigation, for scripting, or to populate frame or iframe elements.
If however as you say in the comment, getting/setting the document's body is enough, you are much easier off using one of the linked examples.
There is also the srcdoc attribute:
<iframe srcdoc="<p><h1>Hello</h1> world</p>"></iframe>
Demo, Polyfill.
In improving my file uploads in an AJAXS env I had the same need. This worked for me in ie8 and ff 22.0. Both the body innerhtml and div innerhtml work.
function copyframedata(data) {
var x = document.getElementById("photo_mgr_frame");
var y = x.contentWindow || x.contentDocument;
if (y.document) y = y.document;
y.getElementById('photo_mgr_mb').innerHTML = data;
}
got it from w3
I came across the same problem but here's an easy fix.
function Run(){
var txt = "<h1>Hello World</h1>";
var frame = document.getElementById('frame');
var frame = (frame.contentWindow || frame.contentDocument);
if (frame.document) frame = frame.document;
frame.open();
frame.write(txt);
frame.close();
}
<iframe id='frame'>
</iframe>
<button onclick='Run()'>Run</button>