Using a variable from a different window - javascript

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

Related

How to alert all content of page on button click with JavaScript

I need to get all the content of page including all codes on JavaScript alert. Please check the code.
function getContent() {
var content = document.getElementsByTagName('html').value;
alert(content);
}
<html>
<head>
</head>
<body>
Some more code..........
Get Content
</body>
</html>
I am trying to execute the function from inside the page and trying to get the value. It is giving me undefined error
.getElementsByTagName() returns a NodeList collection of elements. You need to access the first index with [0]. In addition to this, it does not have a .value property. You're looking for .innerHTML instead.
Note that you also shouldn't make use of onclick, and instead should make use of unobtrusive JavaScript by adding an event listener.
This can be seen in the following:
function getContent() {
var content = document.getElementsByTagName('html')[0].innerHTML;
alert(content);
}
document.getElementsByTagName('a')[0].addEventListener('click', getContent);
<html>
<head></head>
<body>
Some more code..........
Get Content
</body>
</html>
Note: this will not work as expected in a Fiddle, but will work as expected on a proper website.
This can be achieved via the innerHTML field of a DOM element. Consider making the following changes to your getContent() function:
function getContent() {
var { innerHTML } = document.querySelector('html');
alert(innerHTML);
}
<html>
<head>
</head>
<body>
Some more code..........
<p> and some more content </p>
Get Content
</body>
</html>

Calling variable from javascript in an html doc

I work in schools and use google forms to keep track of a number of things.
One of these forms emails people with information from the sheet that is entered.
I have managed to cobble together a good script that provides this service, however, I want it to look good.
My question is simple (or so I believe it is):
When I put in my HTML for the body of the email, how do I call the variables that I have defined earlier in the script?
Do I need to define them in the HTML or can I call them from the JavaScript?
I am not a serious coder by any means but this one has seemed to escape my ability to google it.
Any help would be appreciated.
calling a value of the variable created in javascript, outside the script.
<html>
<script>
var somevariable = "hi"; //this is the variable you create in JavaScript
window.onload = function() {
document.getElementById("blabla").innerHTML = somevariable; //here you send the value of 'somevariable' to html.
}
</script>
<body>
<input type="text" id="blabla" name="someInput"></input>
</body>
</html>
I am not too sure what your code looks like so this is only an attempt to answer what I understand so far.
In you HTML document you don't call variables, you call functions. for example when you click a button, the text would change to what your variable is by calling the onclick Event inside the button, ChangeText() will be the function for the first example:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<button onclick="ChangeText()">Button</button> <!-- onclick event -->
<script>
var p1 = document.getElementById("p1"); //variable created
function ChangeText () {
//when you click the button this function will be called
p1.innerHTML = "Changed text on button click!";
}
</script>
</body>
</html>
You could also call on the load of the document (but this would mean that you would't see what it was before):
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<script>
var p1 = document.getElementById("p1"); //variable created
p1.innerHTML = "Changed text on page load!"; //change text on load
</script>
</body>
</html>
hope this helps.

Creating a variable seen by all opened pages in one window, is it possible?

Is there any way in JavaScript to have a variable that would stay "alive" and accessible across all pages opened within one window?
I have created two pages dog.php and cat.php.
dog.php goes like this:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
MyWord = "Bingo";
document.getElementById("demo").innerHTML = window.MyWord;
</script>
<p>go to the cat page</p>
</body>
</html>
and the cat.php is this:
<!DOCTYPE html>
<html>
<body>
<p id="KittyTalks"></p>
<script>
document.getElementById("KittyTalks").innerHTML = window.MyWord;
</script>
</body>
</html>
However the cat.php reads "undefined" instead of "Bingo", which means that the cat.php page doesn't see the variable MyWord created in dog.php.
Is there any way to make it see that variable?
It's not quite a variable, but you could use Session Storage. To implement your example, you might do:
sessionStorage.setItem('MyWord', 'Bingo');
on the first page, and then
document.getElementById("KittyTalks").innerHTML = sessionStorage.getItem('MyWord');
on the second page.
If you want to get a little fancier, you could define a property. On both pages you would put code like this:
Object.defineProperty(window, "MyWord",
{
get:()=>sessionStorage.getItem("MyWord"),
set:(val)=>sessionStorage.setItem("MyWord", val)
}
);
Then you could use it like a regular variable.
You can use localstorage: https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
Something like this on dog.php:
localStorage.setItem('MyWord', 'Bingo');
and then on cat.php:
var myWord = localStorage.getItem('MyWord');
Use local storage!
http://www.w3schools.com/html/html5_webstorage.asp
But remember that this variable will be visible for all windows/future sessions on the same host!
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

How to add a javascript function inside the body of iframe

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.

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.

Categories