3

我希望我的功课做得很好,在过去的几个小时里搜索互联网并尝试一切,然后再发帖到这里,但我真的很接近说这是不可能的,所以这是我最后的选择。

我想要一个简单的东西(但在 JavaScript 中似乎很难):

  1. 单击按钮-> 打开窗口(使用 window.open)
  2. 在弹出窗口中执行操作并将值返回给父级(开启者)

但我想以系统的方式实现它,为此弹出定义一个回调;就像是:

var wnd = window.open(...)
wnd.callback = function(value) {
    console.log(value);
};

我尝试在弹出窗口 JS 代码中定义回调属性:

var callback = null;

不幸的是,这不起作用,因为...

$('#action').click(function() {
    console.log(callback);
});

...返回我最初设置的那个“null”。

我还尝试在窗口加载后在父窗口中设置回调(通过 window.onload=... 和 $(window).ready()),都没有工作。

我还尝试在子窗口源代码中定义一些方法来在内部注册回调:

function registerCallback(_callback)
{
    callback = _callback; // also window.callback = _callback;
}

但结果相同。

而且我没有更多的想法。当然,使用 window.opener 设置值很简单,但我会失去这个子窗口所需的大部分灵活性(实际上是 DAM 系统的资产选择器)。

如果您有一些想法,请分享。谢谢你一百万!

4

2 回答 2

4

postMessage想到了HTML5 。它旨在完成您想要完成的工作:从一个窗口发布消息并在另一个窗口中处理它。

https://developer.mozilla.org/en/DOM/window.postMessage

需要注意的是,它是一个相对较新的标准,因此较旧的浏览器可能不支持此功能。

http://caniuse.com/#feat=x-doc-messaging


使用起来非常简单:

要从源窗口发送消息:

window.postMessage("message", "*");
//'*' is the target origin, and should be specified for security

要在目标窗口中侦听消息:

window.addEventListener
("message", function(e) {
console.log(e.data); //e.data is the string message that was sent.
}, true);
于 2012-05-25T23:40:55.030 回答
1

After few more hours of experiments, I think, I've found a viable solution for my problem.

The point is to reference jQuery from parent window and trigger a jQuery event on this window (I'm a Mac user but I suppose, jQuery has events working cross-platform, so IE compatibility is not an issue here).

This is my code for click handler on anchor...

$(this).find('a[x-special="select-asset"]').click(function() {
    var evt = jQuery.Event('assetSelect', {
        url:        'this is url',
        closePopup: true,
    });
    var _parent = window.opener;
    _parent.jQuery(_parent.document).trigger(evt);
});

... and this is the code of event handler:

$(document).bind('assetSelect', function (evt) {
    console.log(evt);
});

This solution is fine, if you don't need to distinguish between multiple instances of the asset selection windows (only one window will dispatch "assetSelect" event). I have not found a way to pass a kind of tag parameter to window and then pass it back in event.

Because of this, I've chosen to go along with (at the end, better and visually more pleasant) solution, Fancybox. Unfortunately, there is no way - by default - to distinguish between instances either. Therefore, I've extended Fancybox as I've described in my blog post. I'm not including the full text of blog post here, because is not the topic of this question.

URL of the blog post: http://82517.tumblr.com/post/23798369533/using-fancybox-with-iframe-as-modal-dialog-on-a-web

于 2012-05-26T15:10:09.183 回答