About changing the context where a javascript function runs - javascript

I solved a problem I had, by realizing that if you define a javascript function in a certain context, you cannot call it to run in a different context. Now, I have been exploring ways to accomplish that.
My goal is: I have three windows: The first one is the main window, where my function was created. The second is a newly opened window using window.open. This second window has a button to open the third and last window, making that after opening, that third one should run the same function that was defined in the first window.
I have tried to reference this third window in the main function like this:
(assuming that the name of my window.open variable is w )
var w;
function main() {
console.log(w);
...rest of the code....
}
so I was hoping that it would give a hint to the main function, of the existence of W, the window that I would open later on.
Then, from the second window I would create a button and make an onclick:
w.main;
which wouldn't work...
Is there a different method (or a way to change this one) to make a function aware of the existence of a different context where it was created, so when the moment arrives in the future, is able to run inside of it?
I am reading now about adapting call() to my purpose. Does it make sense, or you would suggest a different way?

Assuming window 1 opens window 2 and window 2 opens window 3
and you are trying to call the main method in window 1 from window 3
window.opener.opener.main();
to set w in window 1 to the window 3 reference when opening it in window 2:
window.opener.w = window.open();
Ok i tested this out.
A dialog opens displaying "test" in window 1 after window 3 opens
window1.html:
<html>
<head>
<script type="text/javascript">
var child = window.open("window2.html", "window2");
function test() {
alert("test");
}
</script>
</head>
<body>
</body>
</html>
window2.html:
<html>
<head>
<script type="text/javascript">
var child = window.open("window3.html", "window3");
</script>
</head>
<body>
</body>
</html>
window3.html:
<html>
<head>
<script type="text/javascript">
window.opener.opener.test();
</script>
</head>
<body>
</body>
</html>

Related

How do I allow my window to open and there be the text the user inputs?

I want the user to be able to open the website and there will be a prompt that will ask the user to tell them about themselves and the text they input display in a new window?
<html>
<head>
<script>
var text = prompt("Tell us something about yourself ");
function newWindow() {
var OpenWindow = window.open("", "slayyyter", "height=300 , width=300");
}
function showText() {
OpenWindow.document.write(text);
}
</script>
</head>
<body>
<button onclick="showText()">A</button>
</body>
</html>
The code has three errors in it. Open the web console (typically by pressing F12) to see messages for some of them.
The prompt string
"Tell us something about
yourself"
has a line feed in it that needs to be removed,
The variable OpenWindow declared in newWindow is not in scope of the code inside showText. If declaring OpenWindow globally, remove var before the variable name inside newWindow to prevent the global variable being shadowed by a local declaration.
newWindow needs to be called
Here's an example that returns the window object instead of saving it in a global variable:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Test</title>
<head>
<script>
"use strict";
var text = prompt("Tell us something about yourself");
function newWindow() {
return window.open("", "slayyyter",
"height=300 , width=300");
}
function showText() {
var openWindow = newWindow();
newWindow().document.write(text);
newWindow.close();
}
</script>
</head>
<body>
<button onclick="showText()"> A </button>
</body>
</html>
Note
document.write is useful for learning exercises in JavaScript, but call document.close to finalize a document after writing to it - it stops the window loading indicator in opened windows.
Seach on "HTML5 document type declaration", "Declaring the character set in HTML" and "when to use strict mode in JavaScript" for more information.
You'll want to use your browser's tools and JavaScript console, which on button click says that OpenWindow is not defined. This is because of scope. OpenWindow only exists where you define it - inside function newWindow. To access it in other functions declare it outside (right under var text will do). You can leave it defined but blank, then assign it later. So under the declaration of "text" just put var OpenWindow;. Then inside newWindow delete "var" from in front of OpenWindow. You may have other issues as I have not tested the code, but that's the main one.
Hints:
read up on scope
read up on browser debug tools, especially JS console
do your tutorials in http://jsfiddle.net or something similar, and you can share examples here when you ask for help.
I'm afraid what you want to achieve isn't doable that easily because there is no direct way to tell the new browser window what you have written in the first window.
You can do it like this however.
Prompt to enter some text
Save the entered text into the browser's localstorage.
Open the same html page using window.open() but append a query string to the url e.g. ?id=new
Make a distinction via code if the site was called with or without a query string. If there's no query string show the prompt dialog, if there is a query string get the text from the localStorage and write it to the browser window.
Use this snippet and save it as test.html
<html>
<head>
<script type="text/javascript">
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('id') == null) {
var text = prompt("Tell us something about yourself");
localStorage.setItem('myText', text);
window.open("test.html?id=new", "slayyyter");
} else {
document.write("You have written: " + localStorage.getItem('myText'));
}
</script>
</head>
</html>
As a side note - window.open() accepts an url as the first parameter. You can't simply enter some text or pass a string containing text - it must be a valid resource e.h. an image, a html file, php,...

Why does this throw an exception in IE 11

Why does the following code throw an 'Unspecified error' (on the appendChild line) in Internet Explorer 11 which I click the button?
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
var popUp = window.open('about:blank');
popUp.document.body.appendChild(document.createElement('div'));
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>
You're using the document of the current page to create the div, try using the document from the popup window
popUp.document.body.appendChild(popUp.document.createElement('div'));
Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). That might be causing the problem if you have popups blocked.
You need to call window.open from an event initiated by the user, e.g. clicking on a link, and that link needs to have target="_blank". Otherwise, Chrome and Firefox will block the popup.
Also, the error is triggered because popUp is not checked for null before attempting to append the div to it. If there's no popup, you can't append an element to it.
(I forgot this bit and Musa made me remember, so thanks) IE will block appending any element created in a different window context from the window context that the element is being appending to. So, instead of creating the DIV node using the current document, you need to create it using the popUp's context.
Summing it all up, this is how it would look the code.
<!DOCTYPE html>
<html>
<head>
<script>
function go()
{
var popUp = window.open('about:blank');
try
{
// Make sure you have a body document when creating the new window....
popUp.document.write("<html><head><title></title></head><body></body>");
popUp.document.body.appendChild(popUp.document.createElement('div'));
}
catch(e)
{
console.log(e);
}
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>

Check Child Window Focus in Javascript

I want to know if the user has focus on the http or https.
So everytime the user clicks on one of the childwindows - i want to know which one is "active".
I checked the W3C. The Page Visibility API
Is there a way to detect if a browser window is not currently active?
But for me it only was working with tabs but not windows.
EDIT: And only tested on the Parentwindow.
Any Help?
Thanks in advance.
Here is what i got.
<html>
<head>
<title>checkfocus</title>
</head>
<body>
Click me.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
var w;
var w2;
function loadChild() {
w = window.open("","",'width=400,height=200');
w.location.href="https://www.facebook.com";
w.moveTo(0,0)
w.addEventListener('focus',function(){
console.log("w")
})
w2 = window.open("","",'width=400,height=200');
w2.moveTo(400,0)
w2.location.href="http://www.facebook.com";
w2.addEventListener('focus',function(){
console.log("w2")
})
}
</script>
</body>
</html>
the Events is fired 2 times in chrome one time when the window is opened and one time location.href is set... but nothing afterwards
try to put the code in a div, put the div in a table and put the table in a top-frame...!

Javascript function call across HTML windows

According to this page I should be able to call parameters and functions of child windows, but it is not working for me.
var w = window.open("index.html");
console.log(w);
console.log(w.foo);
console.log(w) shows that there is a function named foo but console.log(w.foo) outputs undefined. Is this a security issue?
EDIT Here is some more functionality:
child.html (omitting the body):
<head>
<script type="text/javascript">
test = 123 ;
function foo(arg){
//do something
}
</script>
</head>
parent.html:
var w = window.open("child.html");
console.log(w);
//outputs all the methods and parameters
console.log(w.foo);
//outputs 'undefined'
console.log(w.test);
//outputs 'undefined'
EDIT 2 Also I should explain why I need to pass arguments as someone will inevitably ask me why I can't 'just hard code it'. I have an HTML canvas element, and every time the user right clicks, there is a right click menu with the option 'list shapes underneath'.
When the user clicks this menu item, I want to pass a list of all the shapes underneath that click and to display it in a new window. Here are the problems I am facing:
I can't pass it as an argument b/c I don't know whether the window has been loaded (I can't seem to change the onload function either)
I can't have the child window query the parent window b/c the right click menu disappears after clicking it.
The problem is that you are not giving the DOM of the child window a chance to load before trying to inspect its contents.
console.log(w) appeared to work by displaying Window or similar immediately, but in fact it's just that by the time your human fingers got around to expanding the item details in the console, the properties and methods were present.
When I inject a delay with help from a Firebug breakpoint, I can see the child window's properties like this just fine.
This question talks about adding onLoad event listeners for children. Using its accepted answer, how about:
<script type="text/javascript">
// parent.html
var w;
function lol() {
console.log(w.foo);
console.log(w.test);
}
w = window.open("child.html");
console.log(w);
w.addEventListener('load', lol, true);
</script>
(I was also able to achieve success with a 1s setTimeout delay.)
The answer is rather simple if you look at your code logically
The following two calls will only work inside the window you open.
console.log(w.foo);
//outputs 'undefined'
console.log(w.test);
//outputs 'undefined'
i.e.
console.log(foo);
in the parent window javascript, and
console.log(window.parent.foo);
in the child window javascript.

Weird behavior when trying to reuse a popup window

We have a client requirement that has stumped me, embarrassingly enough.
The client has a set of links that need to open in a popup window - if you click on any of the links, it should reuse the same popup window. Easy enough, I thought, so I threw something like this together:
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var popupWin = null;
function openWindow(url) {
if (popupWin == null) {
popupWin = window.open(url,'p2p','');
} else {
if (!popupWin.closed) {
popupWin.location.href = url;
} else {
popupWin = window.open(url,'p2p','');
}
}
popupWin.focus();
}
</script>
</head>
<body marginheight="0" marginwidth="0" leftmargin="0" topmargin="0" bgcolor="#ffffff">
<ul>
<li>Google</li>
<li>FB</li>
<li>Apple</li>
<li>ESPN</li>
</ul>
</body>
</html>
If you put that into an html file, all behaves as expected.
My problem is that when I use the client's intranet URLs per their requirement, the behavior I see is as follows:
Click on one of the popup links (popup link opens in a new window)
Click on another of the popup links (link replaces page opened in the first popup)
Close the popup window.
Click one of the popup links (doesn't matter which, opens in a new popup window as
expected)
Click on another of the popup links (popup opens in a new popup window, not reusing the popup window as expected)
The weird thing is that if I step through the javascript code in Firebug, it correctly gets to the branch of the if statement that determines that the popup window exists and is not closed (so it should be reused), but the line of code:
popupWin.location.href = url;
Ends up opening a new window for some reason.
So, any idea what's going on? I'm guessing something bizarre on the pages that the client wants me to popup is screwing things up in some mysterious fashion, but I can't figure out what it is. Wish I could provide the links to you, but unfortunately they're private.
Thanks much for any help.
Mustafa
Isn't this functionality inherent in HTML? Shouldn't it work without the javascript?

Categories