如何从弹出窗口访问窗口变量?

4

我已经花费了几个小时来解决一个JavaScript问题。我有一个JS函数,可以打开一个弹出窗口:

function openSearchWindow(searchType, targetIdField, targetDescField)

我创建了一个新窗口,并向其设置了两个属性:

var win = window.open(searchPage, searchType + "search", style);
win.targetIdField = targetIdField;
win.targetDescField = targetDescField;

到目前为止,一切都运行得很完美。然而,在我的弹出窗口中,我需要访问之前设置的这两个变量:win.targetIdField和win.targetDescField。

我该如何访问它们?我尝试了几乎所有方法。

编辑-在弹出窗口中,我实际上有一个搜索引擎。当用户单击结果时,有一个JS函数获取所选项目的ID和DESCRIPTION,并将其传回到“opener”窗口,分别放置在targetIdField和targetDescField中。

编辑(2)

一旦在弹出窗口中执行搜索(通过servlet),弹出窗口的URL会更改,但始终位于同一域内。

提前致谢。

卢卡斯。


你最终找到解决方案了吗? - Abe Miessler
4个回答

2

你尝试过通过 window.targetIdField 访问它们吗?如果这样做不起作用,你可以在父窗口上绑定这两个属性(使用 window.targetIdField 而不是 win.targetIdField),然后从你打开的窗口中访问这些属性,使用 window.opener.targetFieldid


谢谢你的回答,freaktm。实际上我试过了,但没有成功。关键是因为把这些变量放在我的父窗口中是没有意义的,因为我需要为每个字段创建一个属性(在父窗口中有一些字段将访问相同的JavaScript函数)。 - LucasM

1
我建议您使用setAttribute和getAttribute,因为这在我所知道的每个浏览器中都得到了支持。
//Setting the properties (in the parent window)
win.setAttribute('targetIdField', targetIdField);
win.setAttribute('targetDescField', targetDescField);

//Accessing the properties (in the pop-up window)
window.getAttribute('targetIdField'); //you might need to use lowercase letters...
//If that doesn't work you can try multiple things
this.getAttribute...

谢谢,dominicbri7!我按照你建议的做法,在打开弹出窗口的函数中设置了这两个属性。但是,当我尝试在弹出窗口中访问它们时:var proptext = window.getAttribute('targetid'); alert(proptext);还尝试使用this.getAttribute... 但是什么都没有发生。 - LucasM
窗口不是一个元素。它没有set或getAttribute方法。你需要使用window.document.body来实现。 - undefined

0

win.contentWindow将为您提供访问新窗口对象的权限。

然后,您可以使用:

win.contentWindow.targetIdField = targetIdField;
win.contentWindow.targetDescField = targetDescField;

为你的新弹出窗口对象设置targetIdFieldtargetDescField变量。

请注意,跨窗口访问仅限于同一域。


谢谢,Soubok。我确实尝试了你的解决方案,但似乎并没有起作用。我仍然无法在弹出窗口内访问那些变量。 - LucasM
弹出窗口(URL)是否在同一域中?窗口和子窗口之间的跨域访问可能会成为一个问题。 - Franck Freiburger
是的。我在想这些属性是否会丢失,因为一旦执行搜索(通过servlet),URL就会更改(到servlet URL),但我们始终在谈论同一个域。 - LucasM
不,我已经在GlassFish控制台上检查过了,但我非常确定这是JS错误。实际上,我实现了一个“临时解决方案”,目前可以工作,但我确实希望这个函数是通用的。 - LucasM

0

从父窗口/打开的窗口访问变量可以通过window.opener.yourVariableName实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接