在关闭 window 时在 IE11/Edge 中调用 removeEventListener 时出错,但在 Chrome 和 Firefox 中有效

Error when calling removeEventListener in IE11/Edge on closed window, yet works in Chrome and Firefox

我创建了一个 JSFiddle 来展示该行为。我观察到 IE11/Edge 以一种方式运行,而 Chrome 和 Firefox 以另一种方式运行,我不确定这两种情况中哪一种是错误或设计缺陷。

https://jsfiddle.net/vuprp9k9/

HTML:

<div id="output">placeholder</div>
<button id="addEvtPopup">Add Event to Pop-up Window</button>
<button id="removeEvtPopup">Remove Event from Pop-up Window</button>
<button id="popupBtn">Open Pop-up Window</button>

JavaScript:

var output = document.getElementById("output");
var addEvtPopupBtn = document.getElementById("addEvtPopup");
var removeEvtPopupBtn = document.getElementById("removeEvtPopup");
var popupBtn = document.getElementById("popupBtn");
var popupWin = null;

function myHandler(evt) {
  output.innerHTML = output.myParam;
}

popupBtn.onclick = function() {
  // Observe the variable referencing the pop-up Window
  popupWin = window.open("", "myPopupWin", "width=100px, height=100px, top=500px, left=-1000px");
};

addEvtPopupBtn.onclick = function() { 
  popupWin.addEventListener("unload", myHandler, false);
  output.innerHTML = "Pop-up Event added";
  output.myParam = "Pop-up Event unloaded";
  popupBtn.eventEnabled = true;
};

removeEvtPopupBtn.onclick = function() {
  // Chrome and Firefox: With pop-up closed, popupWin still has reference to closed pop-up window
  // IE11 and Edge: With pop-up closed, popupWin has no reference to closed pop-up window
  // As a result, the next line will error out in the latter browsers but not in the former browsers
  // In both cases, typeof popupWin evaluates to "object"
  popupWin.removeEventListener("unload", myHandler, false);
  output.innerHTML = "Pop-up Event removed";
  popupBtn.eventEnabled = false;
};

这里发生的事情是我打开一个弹出窗口 window 并向它添加一个事件侦听器。我关闭弹出窗口 window,然后删除它的事件侦听器。

在 Chrome 和 Firefox 中,popupWin.removeEventListener("unload", myHandler, false); 正常进行,因为即使弹出窗口 window 关闭,popupWin 仍然引用弹出窗口 window。对于 IE11 和 Edge,该行会引发错误,因为 popupWin 未引用弹出窗口 window.

请理解我不是在寻找“不要那样做,那样做”的答案。 我想了解为什么 Chrome 和 Firefox 在关闭后仍然包含对弹出窗口 window 的引用,而 IE11/Edge 失去引用。这两种情况中哪一种正确处理了对弹出窗口的引用 window?

更新

仅供参考:以上是在 Windows 10 VM 和 Microsoft Edge 版本 12.10240 中测试的。 VM 由 Microsoft 通过其开发中心提供。

https://dev.windows.com/en-us/microsoft-edge/tools/vms/windows/

因此,至少就我而言,我尚未确认其他版本的 Edge,即 12.x 和 13.x 是否存在丢失引用的问题。

作为 Microsoft Edge 团队的一员,这只是我们的一个错误。我在内部创建了一个问题,并且在(希望)不久的将来的某个时候它会被修复

添加第三个参数可能会有帮助。

.addEventListener("unload", myHandler, true);

它在我的项目中适用于 IE11。

例如

window.addEventListener('scroll', function (){ console.log(152) }, true);