Callback for a popup window in JavaScript

送分小仙女□ 提交于 2019-12-04 17:48:46

HTML5's postMessage comes to mind. It's designed to do exactly what you're trying to accomplish: post messages from one window and process it in another.

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

The caveat is that it's a relatively new standard, so older browsers may not support this functionality.

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


It's pretty simple to use:

To send a message from the source window:

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

To listen for messages in a target window:

window.addEventListener
("message", function(e) {
console.log(e.data); //e.data is the string message that was sent.
}, true);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!