I want to access a variable in iframe from parent index.html.
The index.html:
<!doctype html>
<html lang="en-us">
<head>
<title>Test</title>
</head>
<body>
<p>Test</p>
<div>
<iframe name="myIframe" id="test1" src="index2.html" width="100px" height="100px"></iframe>
</div>
<div>
<script type="text/javascript">
var clickParent = document.getElementById("test1").contentDocument.clicks;
function onClickP() {
console.log("click on parent: " + clickParent);
};
</script>
<button type="button" onClick="onClickP()">Click Parent Button</button>
</div>
</body>
</html>
The iframe index2.html:
<!doctype html>
<html>
<head>
<title>Clicks</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
console.log("click counts: " + clicks)
};
</script>
<button type="button" onClick="onClick()">Click Child Button</button>
</body>
</html>
In the console, the variable clickParent is "undefined". How to fix this and make the variable clickParent = clicks?
This question is not a duplicate of Sharing global javascript variable of a page with an iframe within that page because it is the opposite. I want to access the iframe's variable from the parent, not access parent's variable from the child. My Question, the variable that parent accesses from iframe is "undefined".
Any answers would be appreciated. Thank you.
Possibly a duplicate of this.
Declare global variables in the parent and set them in the iframe document using parent.var_name.
You can also access child vars by creating an object for the child document:
child_iframe = document.getElementById("iframe_id").contentWindow;
alert(child_iframe.var_name);
In my case, I was using the window.name on the parent. For accessing that on iFrame, I was using window.parent.name.
Related
window.opener doesn't work in Chrome. Ok for IE. Do you know why ?
Is it a problme of cross-document interactions ? I don't know why, files are in the same folder on my local computer.
I want the child window could access to the datas (DOM for exemple) of the parent window and modify them.
This is a example :
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<input type="text" id="data" value="1234567" />
Open Child Popup window
<script>
function openChildWindow() {
window.open('child.html','childWindow','width=400,height=400');
}
</script>
</body>
And for the cild window child.html :
<html>
<head>
<title>Child Window</title>
<script>
function initializeMainDiv() {
document.getElementById("mainDiv").innerHTML = "Parent window data field value is: " +
window.opener.document.getElementById("data").value
}
</script>
</head>
<body onload="initializeMainDiv();">
<div id="mainDiv"></div>
</body>
</html>
It doesn't work on my chrome. I don't understand why, the code is simple.
I try with parent.window.openener, but the result is the same.
Allow me to restate my problem. These are the givens:
main.html
<html>
<head>
`<script type="text/javascript" src="js/MyJS.js"></script>;`
</head>
<body>
<script>
document.getElementById("DisplayVar").innerHTML = a;
</script>
<div id="DisplayVar">
</div>
</body>
<html>
MyJs.js
var a = 1;
Nothing is displayed in the "DisplayVar" div, and the developer console says that (a) is undefined. Why is this?
You have to assign innerHTML of the "DisplayVar" div after creating it
<head>
<script type="text/javascript">
// or source to MyJS.js
var a = 1;
</script>
</head>
<body>
<div id="DisplayVar"></div>
<script>
if(document.getElementById("DisplayVar"))
document.getElementById("DisplayVar").innerHTML = a;
</script>
</body>
See codepen, I added a reference to an external js file, and used one of the variables defined there.
I also changed the position of the inline script. It should be placed after the creation of destination div element.
Here is a snippet of code that uses a script to populate the contents of an iframe:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$('iframe').contents().find('body').html('<script>console.log($("div"))<\/script>');
});
</script>
</head>
<body>
<div>Test</div>
<iframe />
</body>
</html>
When executed we see that the iframe has access to the parent's DOM and we see the div being selected by the jQuery selector. The iframe does not have jQuery included but it can access the jQuery object of the parent.
However if we write the same thing via an iframe src inclusion, the behavior is different:
test.html:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div>Test</div>
<iframe src="another.html">
</body>
</html>
another.html:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
console.log($('div'));
});
</script>
</head>
<body>
</body>
</html>
We now see that the page does not list any divs. Further, if we don't include the jQuery js in the child page, it would throw an error.
Note that both pages are in the same domain, so we don't have same-origin policy issues.
My questions are:
Why is the behavior different for the 2 - a. manipulating the iframe DOM from the parent and b. including the iframe content via a src?
Is there a way to make the parent have access to the child and NOT vice-versa?
So the first bit of code gives 1 and the second bit of code gives 0?
That seems correct.
In the first example $ is bound to the parent frame. In the second example, since you have a new instance of jQuery it's bound to the iframe.
In:
$(document).ready(function() {
$('iframe').contents().find('body').html('<script>console.log($("div"))<\/script>');
});
jQuery's html function will do an eval on the script-part of the inserted HTML. That eval will run in the scope of the parent so it uses the parent instance of $.
If you just moved the script to the iframe it will fail because it doesn't have access to $.
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.
I have the following two HTML Documents:
Main.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
var ExamId = "001A";
function open_exam()
{
window.open("exam.html")
}
</script>
</head>
<body>
<input type=button value="Open Exam" onclick="open_exam()">
</body>
</html>
Exam.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function setParentInfo()
{
window.parent.document.ExamID = '001B';
}
</script>
</head>
<body>
<p>Welcome to the Exam!</p>
<input type=button value="Set Parent Info" onclick="setParentInfo()">
</body>
</html>
Main.html brings up Exam.html via the input button. From inside Exam.html I would like to change the variable ExamID on the parent document (i.e.: Main.html). I'm trying to do this via the JavaScript function: setParentInfo().
The above code is not working. Can someone help me come up with the correct code?
Thanks So Much!
Variables are assigned on the window object, not the document object.
Since the value is already set, you can instead read the existing value to verify it:
alert(window.parent.ExamId); // == "001A"
Variable is declared and assigned in parent window so you get reference from your child window.
you can test using alert statement:
alert(window.parent.document.ExamId);
//output::001B