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

how to access a window variable from a popup window?

本文关键字:窗口 访问 变量      更新时间:2023-09-26

我已经浪费了几个小时试图找出如何解决一个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,并将其传递回"打开器"窗口,分别将它们放置在targetIdField和targetDescField中。

编辑(2)

一旦在弹出窗口中执行搜索(通过servlet),弹出窗口的URL就会改变,但它总是在同一个域中。

提前感谢。

卢卡斯。

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

我建议使用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...

win.contentWindow将允许您访问新的窗口对象。

那么你可以使用:

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

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

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

从父窗口/打开器窗口访问变量可以通过window.opener.yourVariableName