How to add a javascript function inside the body of iframe - javascript

i have a html file with iframe and button in it, Is there a way to add a javascript function inside the body of iframe after I click the button?. Here is my code. Thanks
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
function callMe() {
var frame = $('iframe'),
contents = frame.contents(),
body = contents.find('body');
var script2 = document.createElement("script");
script2.type = "text/javascript";
script2.text = " function setEmployeeId(){var employeeId = 0;};"
$(body).append(script2);
};
</script>
<title>sample</title>
</head>
<body>
<iframe src="page2.html">
</iframe>
<button onClick="callMe();">click</button>
</body>
</html>
The result I want is to be like this.
<html>
<head>
<title>sample</title>
</head>
<body>
<iframe>
<html>
<head>
<title></title>
</head>
<body>
<script>
function setemployeeId() {
var employeeId = 0;
};
</script>
</body>
</html>
</iframe>
</body>
</html>

Hopefully you can clarify a few things for me as we go, but I think I have some bad news for you.
Any content that is loaded in an iframe cannot truly edited unless you own the page that is being loaded, in that case you can just bake in whatever you need into the loaded page.
HOWEVER!
You can still access elements in the iframe by using the contentWindow attribute. That is all laid out for you here: How to pick element inside iframe using document.getElementById
Once you've got the element you want to work with, you can create a function in the parent window and then add a call to the parent window's function using window.parent. That's outlined here: Calling a parent window function from an iframe
So if you wanted to make a button in an iframe alter the contents of the iframe you could use
var elem = document.getElementById('myframe1').contentWindow.document.getElementById('myButton')
and then create a function in your parent window
function changeIt(){
document.getElementById('thingToChangeInIframe_ItsIDintheIframe').property = 'value';
}
and append it to the button with the code
elem.setAttribute('onclick', 'changeIt();');
If you have any clarifications to what you need just comment and we'll work those out. I'm sorry this doesn't use much jQuery but that's not really my forte, but I think the pure javascript is relatively self explanatory.
EDIT: I should clarify that if the iframe is on another domain then your options are pretty much all eliminated. For security reasons you can't mess with the settings on other people's pages when you load them in an iframe.

Related

javascript: is it possible to target div of another file?

Let me explain the purpose of this. I'm using some CMS and I'm trying to customize it with php scripts of my own that I embedded to the home page with IFRAME. My php script gives back some links which I would like to open outside that IFRAME - as a part of some other CMS block on the homepage. The idea is to target (from my php script) the div of that CMS block which is already showing some data. Is that possible?
If you need to access <div> or any other element of parent window from its child iframe
USE:
var elem=window.parent.document.getElementById('target');
inside <script> tag of iframe's document.
ex.
file: index.html (Give any name).
<html>
<body>
<div id="div_to_use_from_parent">Blah!</div>
<iframe src="xyz.php" width="xx" height="xx"></iframe>
</body>
</html>
file: xyz.php (same as src of iframe)
<?php
echo<<<html
<html>
<head>
<script type="text/javascript">
function do_blah(){
var elem=window.parent.document.getElementById('div_to_use_from_parent');
elem.innerHTML="iframe changed My Content!";
}
</script>
</head>
<body onLoad="do_blah();">
This is iframe
</body>
</html>
html;
?>
OR
if you need to access element in iframe from parent window
USE:
var iframe = document.getElementById('idOfIframe');
var frame = iframe.contentDocument || iframe.contentWindow.document;
var yourDiv= frame.getElementById('div_you_want');
inside <script> tag of parent window's document.
ex.
file: index.html (Give any name).
<html>
<head>
<script type="text/javascript">
window.onload=function(){
var iframe = document.getElementById('idOfIframe');
var frame = iframe.contentDocument || iframe.contentWindow.document;
var elem= frame.getElementById('div_from_iframe');
elem.innerHTML+="<br /> And Parent window added this!";
};
</script>
</head>
<body>
<div id="div_to_use_from_parent">Blah!</div>
<iframe src="xyz.php" width="xx" height="xx"></iframe>
</body>
</html>
file: xyz.php (same as src of iframe)
<?php
echo<<<html
<html>
<body>
<div id="div_from_iframe"> This div from iframe</div>
</body>
</html>
html;
?>
parent window is the one in which original html(index.html) document along with your iframe(xyz.php) resides.
Hope it helps :-)!
var iframe = document.getElementById('idOfIframe');
var frame = iframe.contentDocument || iframe.contentWindow.document;
var yourDiv= frame.getElementById('div_you_want');
From the page running inside the <iframe> you can refer to the parent page as window.parent, and perform actions as you normally would.
parent.document.getElementById('target_div').innerHTML = 'New content.';
Note JavaScript's cross-domain restrictions apply. You can only do that if both pages belong to the same domain.
In case of links, you can include to your <a> tags the attribute target="_parent", or set it as base target to apply to all links.
<head>
...
<base target="_parent">
</head>
You can also target a link to another iframe, all you have to do is set a name="iframe_name" to it and set target="iframe_name" to all links that should open in that area.

Access a variable of iframe from parent

script of iframe
<script type="text/javascript" >
var a=5;
</script>
script of parent window
<script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>
I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.
Using contentWindow instead of contentDocument works for me:
var check = document.getElementById("iframeid").contentWindow.a;
Also, ensure that the domains match and that you are using a webserver to test (I got a protocol warning when testing from the file system).
UPDATE: You're almost definitely better to use the postMessage API.
One method that has always worked reliably for me is for the iFrame to give its parent a reference to its own window when it first loads. The parent can then access all the variables through that reference. This does require that the parent is loaded before the iFrame, but for me that is usually the case.
So in the parent
var iFrameWin;
Then in the iFrame at some point after it has loaded and settled down
parent.iFrameWin = window; //parent now has a ref to the iframe's window
Then, in the parent when it wants a global var contents from the iFrame
alert(iFrameWin.ivar); // shows value if the global 'ivar' in the iFrame
script of iframe:
var a = 5;
window.parent.postMessage(['varA', a], '*'); // put this in some sort of function, ready, or whatever - you can call it multiple times if you need to as the code in the parent is an eventListener
script of parent window:
var b;
// you might want to write these into if statements to make sure that e.data[0] is varA if you have multiple messages coming across
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', function(e) {
b = e.data[1];
}, false);
} else if (typeof window.attachEvent != 'undefined') { // this part is for IE8
window.attachEvent('onmessage', function(e) {
b = e.data; // you'll probably have to play around with this part as I can't remember exactly how it comes across in IE8 -- i think it will involve slice() iirc
});
}
Most of my knowledge on this topic comes from Ben Vinegar's talk on Seamless iFrames
This is a cross-domain "okay" method to deal wit this stuff. I'm sure there are some security holes, just as with anything on the web.
See if this works for you:
i created this parent.html page and put an iframe in it with a text input which will show the value passed from iframe window:
<html>
<head>
<title>IFrame Example</title>
<script language="javascript">
function hello(string){
var name=string
document.getElementById('myAnchor').value=name;
}
</script>
</head>
<body>
<iframe namne="iframe" id="iframe_id" src="inputForm.html" height="150" >
</iframe>
Name: <input type="text" id="myAnchor" >
</body>
</html>
and this iframe content page:
<html>
<head>
<title>IFrame Child Example</title>
</head>
<body>
<form name="frm2" >
<h1><font color="#000099">Input Form</font></h1>
<p>Name : </p><input type="text" name="resp" id="input" value=""/>
<input type="button" onclick="parent.hello(this.form.resp.value);" value="Submit" />
</form>
</body>
</html>
clicking the button i get the value in my parent window.
Play with it if you get something with this one.
document.getElementById('ID_OF_IFRAME').document.getElementById('f1')
Note that cross-domain restrictions will still apply.
This is how SharePoint do it when passing argument values from the parent window to the iframe. It's simple, but it works.
<html>
<body>
<iframe id="iframe1"></iframe>
<script type="text/javascript">
var ifr = window.document.getElementById("iframe1");
ifr.dialogArgs = "Hello from the other side.";
ifr.src = "iframeContent.html"
</script>
</body>
</html>
Inside iframeContent.html:
<html>
<body>
<input type="button" value="Click Me!" onclick="alert(window.frameElement.dialogArgs);" />
</body>
</html>
The other way around (accessing ifr.dialogArgs from the parent window after having its value modified by the iframe document) also works.

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

Display iframe div contents on parent page

I'm sure this is pretty basic, but I can't seem to get any of the solutions I've found to work for me. Basically, I need to get the contents of a div from an iframe, and write them to a div in the parent page. This is what I have:
<iframe src="slideshows/slideshow/case2.html" frameborder=0 scrolling="no"
id="frame1" name="frame1"></iframe>
<div id="caption">
<script type="text/javascript">
var caption = frame1.document.getElementById('slidecaption');
document.write(caption);
</script>
</div>
'slidecaption' is the name of Id in the iframe that I'm trying to grab.
All I get is "null". Is it because the iframe contents haven't loaded yet? If so, how do I delay until the iframe has loaded?
Thanks,
Scott
Thanks to both of you for your help. I figured it out, based on Márcio's idea:
I put the function in the parent page:
<script type="text/javascript">
function send() {
document.getElementById('slidecaption').innerHTML =
frame1.document.getElementById('slidecaption').innerHTML}
</script>
And I put the call in the iframe document:
<body onload="parent.send();">
Regards,
Scott
I'm not sure this is the only thing you need to do, but you certainly need to retrieve frame1 from the dom.
<script type="text/javascript">
var frame1 = document.getElementById('frame1');
var caption = frame1.contentWindow.document.getElementById('slidecaption');
document.write(caption);
</script>

Accessing a javascript function in a nested iframe in IE

I currently have a page structure that consists of a page(Parent) that includes an iframe(iframe0) and inside that iframe I have another iframe(iframe1). In iframe1 I have a javascript function that I am trying to call from Parent. In Firefox/Chrome/Safari I am able to call this function with the following code:
frames["iframe0"]["iframe1"].functionName();
However, in Internet Explorer the above code does not work and it returns the error "Object doesn't support this property or method". I have tried some other ways to access the method with them all returning the same error.
window.frames.iframe0[iframe1].functionName();
window.iframe0.iframe1.functionName();
window.frames.iframe0.frames.iframe1.functionName();
I even tried calling a function in iframe0 that called the function in iframe1 and that didn't even work.
Anyone have any idea on how to access a javascript function that is nested in an iframe that is 2 levels deep?
Thanks.
Update:
After looking into the problem further, I have found that the problem I am dealing with is not related what I have asked. The answer ylebre gave below answers the question I have asked, and there for will me marked as the answer. I will probably start another question describing my problem in more detail.
I've provided an example using 3 HTML files. The outermost is test.html which has an iframe containing iframe1.html. In turn, iframe1.html contains an iframe containing iframe2.html. I'm hoping this is the kind of setup that you have in mind.
Basicly, you can call the iframe function using iframe.contentWindow.myfunc();
Using contentWindow.document you can then access the second level iframe.
The example function 'doit()' calls a function in the parent, first iframe and second iframe.
Hope this helps!
<!------- test.html -------->
<html>
<head>
<script type="text/javascript">
function parent_function() {
alert('parent');
}
function doit() {
parent_function();
document.getElementsByTagName('iframe')[0].contentWindow.iframe1_function();
document.getElementsByTagName('iframe')[0].contentWindow.document.getElementsByTagName('iframe')[0].contentWindow.iframe2_function();
}
</script>
</head>
<body>
main
do it
<iframe src='iframe1.html'>
</body>
</html>
<!------- iframe1.html -------->
<html>
<head>
<script type="text/javascript">
function iframe1_function() {
alert('iframe1');
}
</script>
</head>
<body>
frame1
<iframe src='iframe2.html'>
</body>
</html>
<!------- iframe2.html -------->
<html>
<head>
<script type="text/javascript">
function iframe2_function() {
alert('iframe2');
}
</script>
</head>
<body>
frame2
</body>
</html>
A fast way to select an iframe is to select it in the dom explorer, then in the js console, you can run $0.contentWindow.myFunction()

Categories