How to call function of another iframe - javascript

I'm trying to call iframe2 function from iframe1
document.getElementById('cDiv').contentWindow.toggle_main();
var iframe = document.getElementsByTagName('iframe')[1];
iframe.contentWindow.myFunction();
The console is returning Uncaught TypeError: Cannot read property 'contentWindow' of undefined
I have also tried:
window.frames['iframe2'].toggle_main();
The function in iframe2 is called:
<script>
window.myFunction = function(args) {
alert("called");
}
</script>
The iframes are defined as:
<DIV id="cgDiv">
<IFRAME id="contentGenerator" SCROLLING="No" name ="iframe1" src="outlook.html">
</IFRAME>
</DIV>
<DIV id="cDiv">
<IFRAME id="content" SCROLLING="AUTO" verticalscrolling="yes" NAME = "iframe2" src="index.html">
</IFRAME>
</DIV>
Ideas on where the problem should be?

Javascript can't access functions in an IFrame directly. IFrames can access functions in their parent though.
So if your main page exposes a method RegisterCallback for instance, the IFrame can call it with one of its functions as parameter. The page can then store a reference to the function and call it at another time (with any parameters...)
UPDATE: Added example code
The code below is two files; index.html which is the master page with iframe(s), and child.html which is the page inside the iframe(s).
I've committed the example to github and you can test it by following this link. Due to browser security restrictions the code must be loaded from the same webserver and doesn't work if run directly from the filesystem.
I've intentionally included the child iframe twice to illustrate that any number of children can be registered with this technique. I leave it as an excercise to the reader to add a third iframe... :)
index.html
<html>
<body style="background:#efe">
<h1>This is the master page</h1>
<p><button id="setChildButton" type="button">Make child blue</button></p>
<iframe src="child.html"></iframe>
<iframe src="child.html"></iframe>
</body>
</html>
<script>
var childCallbacks = [];
function registerChild(callback){
console.log('Registering child callback');
childCallbacks.push(callback);
}
function onButtonClick(){
for (var i=0; i < childCallbacks.length; i++){
var callback = childCallbacks[i];
callback('blue');
}
}
window.onload = function(){
document
.getElementById('setChildButton')
.addEventListener('click', onButtonClick);
};
</script>
The javascript has a function registerChild() that it never calls itself, but can be called from child pages to register their endpoints.
When the button is clicked, all registered callbacks are called with the string "blue". It is then up to the childs endpoint to do something good with that. In this case changing its own background color.
child.html
<html>
<body id="childBody" style="background:#fee">
<h2>This is the child page</h2>
</body>
</html>
<script>
function setBackground(color){
var body = document.getElementById('childBody');
body.style.backgroundColor = color;
}
window.onload = function(){
if (parent && parent.registerChild){
console.log('registering with parent');
parent.registerChild(setBackground);
}
};
</script>
The javascript of the child checks if there is a parent (it is running inside an iframe) and that the parent provides a function called registerChild(). It then calls that function with a reference to its own function setBackground().
When the parent later calls the callback with the string "blue", it turns around and sets its own bodys background color to that value.

If all your documents share same origin, it should work, so calling
window.parent.frames['other frame name'].contentWindow['func']()
from within some frame will invoke func from neigbour iframe.
Behold hacky simplistic datauri example in Firefox (Chrome considers dataURI documents as always different origin, so it raises security exception)
data:text/html;charset=utf-8,<iframe id="a" src="data:text/html,<h1 id=a>0</h1><script>function inc(){a.innerHTML++}</script>"></iframe><iframe id="b" src="data:text/html,<button onclick=window.parent.frames.a.contentWindow['inc']()>inc in prevous frame</button>"></iframe>

// First iframe called (ifr_url) in Master page.
// Second iframe called (ifr_tab5) inside the master page.
// I want to call function (Hallow()) in second iframe.
var win = document.getElementById("ifr_url"); // reference to iframe's window
var doc = win.contentDocument? win.contentDocument : win.contentWindow.document;
var form = doc.getElementById('ifr_tab5').contentWindow.Hallow();

Related

Why DOMNodeRemoved event works only once?

in the web-app I'm developing I'd need to dynamically create/remove iframe elements and to catch the corresponding remove events.
This is the relevant html:
index.html
<main>
[..]
<iframe id="iframe_id" width="700" height="650" src=""></iframe>
<div class="theday" id="js-theday"></div>
[..]
</main>
<script src="app.js"></script>
<script type="text/javascript">
function closeIFrame() {
$('#iframe_id').remove();
}
[..]
</script>
In app.js I'm catching the remove event sent in closeIFrame()
$('#iframe_id').on('DOMNodeRemoved', function() {
}
In the first run, when the iframe calls parent.closeIFrame(), app.js receives correctly the
DOMNodeRemoved and do stuffs.
At some point, I'd need to recreate the iframe element. In app.js
function recreate_iframe_html() {
const target = document.querySelector('#js-theday');
var new_iframe = document.createElement('iframe');
new_iframe.setAttribute('id', 'iframe_id');
new_iframe.width = 700;
new_iframe.height = 650;
new_iframe.src = '';
target.parentNode.insertBefore(new_iframe, target);
}
[..]
recreate_iframe_html();
When the new iframe calls parent.closeIFrame(), the iframe is correctly removed but app.js does not detect the DOMNodeRemoved event.
Why is that?
Thank you for your help.
.on('DOMNodeRemoved') only works on the items returned by the query (that is, #iframe_id). It does not stick around to listen to newly created items with the same id.
You need to add another listener when creating the new iframe.

make HTML page's element accessible in another HTML page

I have an HTML page say main.html which has an iframe (say id="myFrame")showing child.html page. Both of these pages have a button called "Hide frame". The onclick of these buttons calls hideFrame() JS function which is declared in main.js file. The hideFrame() function just change the display of myFrame to "none".
function hideFrame(){
document.getElementById("myFrame").style.display = "none";
}
The myFrame is in main.html file so the button in main.html when calls the hideFrame() function, it works. The frame gets hidden. But the same is not working if I call the function from child.html page.
How can I access this element (myFrame) form child.html page?
you should use the main.html's window object to assign the function to. So instead of
function hideFrame(){
document.getElementById("myFrame").style.display = "none";
}
you would do something like
window.hideFrame = function(){
document.getElementById("myFrame").style.display = "none";
}
Now the function is globally scoped on main.html's window.
The child frame has it's own window object. You need access to the parent window object to call the function from child.html.
From main.html, you can call hideFrame normally on click onclick = hideFrame(), but in child.html, you should put onclick = window.parent.hideFrame()
Instead of using an iFrame, I would use jquery to load in segments of html files from other files.
If that is not possible, you could inject Javascript code into the child frame that references objects in the parent. Ex:
child:
<script>
var x;
</script>
parent:
<script>
$("#myFrame").x = function(){
functionality / reference definitions
}
</script>
It took a while to understand what you are saying. From what I understand, you want to get access to an element on the top window from inside an iframe. Here is what to get access to the parent window:
var _parent = window.parent,
_parent_dom = _parent.document;
Then to get access to an element from the parent page (in this case #myFrame):
var my_frame = _parent_dom.getElementById("myFrame");

`ImportNode` in Firefox and extracting an element from an `iframe`

I am trying to understand importNode in html using the following example.
Suppose we have a content.html:
<html>
<body>
<nav id="sidebar1" class="sidebar">
Hi there!
</nav>
</body>
</html>
and a main.html:
<html>
<body>
<iframe src='content.html' hidden='true'></iframe>
<script>
var idframe = document.getElementsByTagName("iframe")[0];
var oldNode = idframe.contentWindow.document.getElementsByTagName("nav")[0];
var newNode = document.importNode(oldNode, true);
document.getElementsByTagName("body")[0].appendChild(newNode);
alert("HI!!!");
</script>
</body>
</html>
I am getting the error:
TypeError: Argument 1 of Document.importNode is not an object.
var newNode = document.importNode(oldNode, true);
What is the proper way to get an element form an iframe and insert it into my html?
You can only access content of the iframe document after the iframe document has been loaded. This can be accomplished different ways:
either by putting your accessing code into load handler of the main (that contains iframe element) document window,
or inside a DOMContentLoaded event listener of the document loaded in iframe.
Below is example of using load event of window of the main document:
window.addEventListener('load', function() {
var iframe = document.getElementsByTagName("iframe")[0];
var oldNode = iframe.contentWindow.document.getElementById("myNode");
var newNode = document.importNode(oldNode, true);
document.body.insertBefore(newNode, document.body.firstChild);
}, false);
Otherwise, iframe content is not yet loaded when you try to access it.
See the live example at JSFiddle (iframe content is placed encoded in the srcdoc attribute of the iframe just because I'm not aware of ability to create subdocuments at JSFiddle without creating a separate fiddle).

Get IFrame's document, from JavaScript in main document

I have this HTML code:
<html>
<head>
<script type="text/javascript">
function GetDoc(x)
{
return x.document ||
x.contentDocument ||
x.contentWindow.document;
}
function DoStuff()
{
var fr = document.all["myframe"];
while(fr.ariaBusy) { }
var doc = GetDoc(fr);
if (doc == document)
alert("Bad");
else
alert("Good");
}
</script>
</head>
<body>
<iframe id="myframe" src="http://example.com" width="100%" height="100%" onload="DoStuff()"></iframe>
</body>
</html>
The problem is that I get message "Bad". That mean that the document of iframe is not got correctly, and what is actualy returned by GetDoc function is the parent document.
I would be thankful, if you told where I do my mistake. (I want to get document hosted in IFrame.)
Thank you.
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). This is because of the browser's Same Origin Policy.
The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.
For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
You can also use:
document.querySelector('iframe').contentDocument

How to add a click event to p elements in iframe (using jQuery)

How to add a click event to <p> elements in iframe (using jQuery)
<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
There's a special jQuery function that does that: .contents(). See the example for how it's works.
Your best best bet is to invoke the iframe AS LONG AS it's part of your domain.
iframe.html
<html>
<head>
<script>
window.MyMethod = function()
{
$('p').click();
}
</script>
</head>
<body></body>
</html>
And then use
document.getElementById('targetFrame').contentWindow.MyMethod();
To invoke that function.
another way is to access the iframe via window.frames.
<iframe name="myIframe" src="iframe.html"/>
and the javascript
child_frame = window.frames['myIframe'].document;
$('p',child_frame).click(function(){
alert('This click as bound via the parent frame')
});
That should work fine.
Wanted to add this, as a complete, copy-paste solution (works on Firefox and Chrome). Sometimes it is easy to miss to remember to call the event after the document, and so the iframe, is fully loaded:
$('#iframe').on('load', function() {
$('#iframe').contents().find('#div-in-iframe').click(function() {
// ...
});
});
The iframe must be on the same domain for this to work.
By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:
jQuery("p", document.frames["oframe"].document).click(...);
To access any element from within an iframe, a simple JavaScript approach is as follows:
var iframe = document.getElementById("iframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow;
// Get HTML element
var iframeHtml = iframeDoc.getElementsByTagName("html")[0];
Now you can select any element using this html element
iframeHtml.getElementById("someElement");
Now, you can bind any event you want to this element. Hope this helps. Sorry for incorrect English.

Categories

Resources