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 functio开发者_StackOverflow中文版n 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.
精彩评论