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.
Related
I'm new to JavaScript and I cannot understand why my html isn't changing?
I have an Iframe and I'm trying to change the .innerHTML of the span class that the Iframe has created in the DOM.
In the DOM structure, the class is called <span class="weather-location">China</span>
I'm just trying to access this by changing it's innerHTML to Taiwan instead.
here is my code:
<html>
<head>
<title>test</title>
</head>
<body onload="myFunction()">
<iframe class="weather" width="100%" height="600px" frameBorder="0"
src="(this is my iframe src code)></iframe>
<script type="text/javascript">
function myFunction() {
document.getElementsByClassName("weather-location")[0].innerHTML = "Taiwan";
}
</script>
</body>
</html>
When I test it in the console log, it brings up that weather-location as [] but whats also bizarre is when I use the selector tool to hover on that weather-location class and go back and re-type in the code it in the console, it changes the class how I wanted?
Also, I don't know if this helps but when it shows up as [] in chrome a little i box pops up saying "value below was evaluated just now".
You can't change the innerHTML of iframes if it's on another domain.
https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe
This kind of iframe is like a window into another webpage you have no control over.
If it is on the same domain you can use something like
var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );
SO Question: accessing a form that is in an iframe
Credit to : #le_m
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.
I want to open a new window in JavaScript, and show some data from the opener window. Based on something I read I made this:
MainWindow.html
<html>
<head>
<script>
function OpenNewWindow()
{
this.MainWindowData = 123123;
document.write(this.MainWindowData);
var wnd = window.open("NewWindow.html");
wnd.NewWindowData = 787878;
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="OpenNewWindow()">
</body>
</html>
NewWindow.html:
<html>
<head>
<script>
function ShowData()
{
document.write("NewWindowData: " + this.NewWindowData + "<br />");
document.write("MainWindowData: " + window.opener.MainWindowData);
}
</script>
</head>
<body>
<input type="button" value="Show Data" onclick="ShowData()">
</body>
</html>
The problem is that both variables remain undefined.
Thanks for the help in advance.
The problem isn't the variables you're creating, it's that document.write wipes out the window's content when you call it any time except during initial rendering, and so wipes out the variables you're creating after you create them. So you don't want to use it after initial rendering.
If you change your document.write calls to (say) document.getElementById('someid').innerHTML = ...; or you use document.createElement, you'll get more successful results.
Here are your pages, just changing document.write to using document.createElement, which makes them work.
Main window: Live Copy | Source
<html>
<head>
<script>
function OpenNewWindow()
{
this.MainWindowData = 123123;
var wnd = window.open("http://jsbin.com/uvocos/1");
wnd.NewWindowData = 787878;
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="OpenNewWindow()">
</body>
</html>
Popup window: Live Copy | Source
<html>
<head>
<script>
function ShowData()
{
display("NewWindowData: " + this.NewWindowData);
display("MainWindowData: " + window.opener.MainWindowData);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p)
}
</script>
</head>
<body>
<input type="button" value="Show Data" onclick="ShowData()">
</body>
</html>
The createElement is in the display function I added to the popup.
Separately: I would probably use window rather than this to create the variable. this will actually be window the way you're calling your functions, so it works, but there are other ways to call functions where it wouldn't work, and using window.foo = ...; would.
Finally: I'm not certain that your putting a variable on the popup immediately after opening it (your NewWindowData) will work reliably, although it does in the above (for me). Usually rather than that, I have the popup pull the data from the opener (your MainWindowData variable) and/or pass the data to the popup via the query string.
Your attempt is actually pretty close but using this. is probably causing issues.
In the parent window, use:
var newWindowVariable = 'Something';
In the new window, use:
var myVariable = window.opener.newWindowVariable;
This is probably the easiest way to accomplish what you're trying to do.
Use LocalStorage.
/* Page A */
window.localStorage.setItem("NewWindowData ", "787878");
/* Page B */
var stringValue = window.localStorage.getItem("NewWindowData");
Then you can convert to int, or whatever you want to cast it to.
If you want to get the value from your parent window you can use in the popup window.
window.opener.document.getElementById('idOfelement').value
example
I have two level parent-child iframe hierarchy in my HTML pages. I want to get an object of parent window document in its child document for some manipulation. I works majorly with Google Chrome.
parent.document gives 'undefined' in Google Chrome, while in Mozilla it works fine. What's the catch?
For reference, please find below the content of the three files demonstrating the issue,
First file: 'one.html'
<html>
<head>
</head>
<body>
<input type="hidden" id="one_1" name="one_1" />
<iframe id="one" name="one" src="two.html">
</body>
</html>
Second file: 'two.html'
<html>
<head>
</head>
<body>
<input type="hidden" id="two_1" name="two_1" />
<iframe id="two" name="two" src="three.html">
</body>
</html>
Third file: 'three.html'
<html>
<head>
<script type="text/javascript">
function callme() {
alert(parent.document)
alert(top.document)
}
</script>
</head>
<body>
<input type="hidden" id="three_1" name="three_1" />
<button id="click" name="click" onclick="return callme()">Click Me</button>
</body>
</html>
Assuming that 'one.html' is opened with Google Chrome, when I click on the 'Click Me' button, two successive alert boxes appears with 'undefined' value. When I open 'one.html' in Mozilla, it gives two 'objectHTMLDocument' valued alert boxes appears.
Please find below the console messages while clicking on 'Click Me' button,
Unsafe JavaScript attempt to access frame with URL file:///C:/Users/user/Desktop/two.html from frame with URL file:///C:/Users/user/Desktop/three.html. Domains, protocols and ports must match.
three.html:6
callme three.html:6
onclick three.html:13
Unsafe JavaScript attempt to access frame with URL file:///C:/Users/user/Desktop/one.html from frame with URL file:///C:/Users/user/Desktop/three.html. Domains, protocols and ports must match.
three.html:7
callme three.html:7
onclick three.html:13
Thanks in advance.
I would inject from top-down as opposed to accessing bottom-up. I would set a variable in an iFrame by selecting it and storing it into a variable like so:
var frame = document.getElementById('one');
And then inject a reference to the parent:
frame.contentWindow.frame_parent_reference = window;
And then perform this in the next child iFrame replacing "one" with "two". That way, by third.html, we don't ask for parent or top, but can do the following:
alert(frame_parent_reference.document);
alert(frame_parent_reference.frame_parent_reference.document);
Perhaps not super elegant but it definitely gives you a lot of control (and you can check if the custom reference exists for security).
Good luck!
I would like access the IFrame element available in the main page from the IFrame source page using JavaScript
Here is my main Page
<html>
<body>
<IFrame id="page-container" src="http://stackoverflow.com"
width="200px" height="200px">
</IFrame>
</body>
</html>
Child Page
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"/>
<script type="text/javascript" >
$(document).ready(function(){
var containerFrame= $('#page-container');
//var containerFrame=document.frames["page-container"];
//var containerFrame=document.frames["page-container"];
//var containerFrame=document.parent.frames["page-container"];
});
</script>
<body>
<div>some content..</div>
</body>
</html>
I am getting undefined for all my tries.
How it can be done? Is it possible?
Edit: I tried loading a cross domain page.
In IE i am getting error ' for security reason framing is not allowed' and also
domains, protocols and port must match. Can we achieve this any way?
var containerFrame = $('#page-container', window.parent.document)
This should firstly reference the parent of the window and then look for the iframe div
You need to specify the context to search for #page-container in, which in this case will be the parent window.
var containerFrame = $('#page-container', window.parent.document);