cross-window javascript events

為{幸葍}努か 提交于 2019-12-05 07:48:35

OK, when I find the "opener" page element and assign handlers this way:

// in the popup page
$(function() {
  var openerElement = window.opener.document.getElementById(theElementId);
  $(openerElement).click(function() {
    alert("Hello World!");
  });
});

Then, to my surprise, native "real" events work just fine. However, custom events fired from the opener page do not get picked up by the popup page. That sort of makes sense, as each page has its own little jQuery universe. I was apparently wrong however about the browser not propagating native events, so thanks for today's learning experience!!

more info — From the popup window (and similarly from any child <iframe> of the main document), you can also use

var thing_in_main_window = window.opener.$('#thingId');

to find stuff in the opener window. However, simply using the jQuery object in the popup page to find that element cannot work, because jQuery will not traverse the "window.opener" link and go hunting for the element there. When you call $('#thingId') on the popup page, jQuery is just going to called document.getElementById('thingId') using the document object for the popup page. If there's no element called "thingId" on that page, it won't be found.

original answer:

I don't think that what you're trying to do will work. The browser is not going to trigger any event handlers in a window different from the one containing the target element.

You can, however, catch the event in one window and then trigger a custom event in the other window. When you do that, you're probably going to want to trigger the event through the jQuery object on that page. In other words, you'd do this:

$('#thing').click(function() {
  otherWindow.jQuery.trigger("thing-clicked");
});

Thanks to Pointy for the answer. I experimented with this and want share my findings. You can actually define your event listeners in the popup window without referencing the opener:

in the page opened as popup:

$(document).on("foo", function() { 
  alert("foo"); 
});

in the page which opens the popup:

var popup = window.open("popup.html", "_blank", "width=500");
$("#trigger-button").on("click", function() {
  popup.$(popup.document).trigger("foo");
});

The secret is: even if you invoke jQuery from popup window object, you can't use selectors directly, because jQuery will try to find elements in the parent (opener) window.

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