跨HTML窗口的Javascript函数调用

Javascript function call across HTML windows

本文关键字:Javascript 函数调用 窗口 HTML      更新时间:2023-09-26

根据这个页面,我应该能够调用子窗口的参数和函数,但它不适合我。

var w = window.open("index.html");
console.log(w);
console.log(w.foo);

console.log(w)表示存在一个名为foo的函数,而console.log(w.foo)输出undefined。这是安全问题吗?


EDIT下面是一些更多的功能:

child.html(省略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我也应该解释为什么我需要传递参数,因为有人会不可避免地问我为什么我不能"只是硬编码它"。我有一个HTML画布元素,每次用户右键单击时,都会出现一个右键菜单,其中包含"下面的列表形状"选项。

当用户单击这个菜单项时,我想传递一个所有形状的列表在点击下面,并在一个新的窗口中显示它。以下是我面临的问题:

  1. 我不能将其作为参数传递b/c我不知道窗口是否已加载(我似乎无法改变onload函数)

  2. 我不能让子窗口查询父窗口b/c右键菜单消失后点击它

问题是,在尝试检查其子窗口的内容之前,您没有给其子窗口的DOM一个加载的机会。

console.log(w)似乎可以通过立即显示Window或类似的内容来工作,但实际上,当你的手指在控制台上展开项目细节时,属性和方法已经出现。

当我在Firebug断点的帮助下注入延迟时,我可以像这样看到子窗口的属性。

这个问题讨论的是为子节点添加onLoad事件监听器。使用其可接受的答案,如何:

<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>

(我也能够成功地获得1s setTimeout延迟)

如果你从逻辑上看你的代码,答案是相当简单的

下面的两个调用将只在您打开的窗口内工作。

console.log(w.foo);
//outputs 'undefined'
console.log(w.test);
//outputs 'undefined'

console.log(foo);

在父窗口javascript,和

console.log(window.parent.foo);