javascript - 如何将关闭事件绑定(bind)到 window.open()

标签 javascript jquery

我有以下函数可以在弹出窗口中打开网址:

function windowPopup(url, width, height) {
  // center 
  var left = (screen.width / 2) - (width / 2),
      top = (screen.height / 2) - (height / 2);

  handle=window.open(
    url,
    "",
    "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=" + 
    width + ",height=" + height + ",top=" + top + ",left=" + left
  );
}

我希望能够检测到此窗口何时关闭并执行一些代码。如何使用函数中的句柄来绑定(bind)卸载或关闭?

我想知道有人分享到 Twitter 后窗口是否关闭:

windowPopup("https://twitter.com/intent/tweet/?text=Check%20out%20this%20website!&url=https%3A%2F%2Fgoogle.com%2F", 500, 300);

更新

我更新了拉尔的建议:

function windowPopup(url, width, height) {
  // center 
  var left = (screen.width / 2) - (width / 2),
      top = (screen.height / 2) - (height / 2);



  handle=window.open(
    url,
    "",
    "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=" + 
    width + ",height=" + height + ",top=" + top + ",left=" + left
  );

  handle.onbeforeunload = function() {
    alert('Bye!');
  }

}

虽然这对某些弹出窗口有效,但当我关闭 Twitter 窗口时却不起作用......

最佳答案

您正在寻找 beforeunload 事件:

handle.onbeforeunload = function() {
  console.log('Bye!');
}

关于javascript - 如何将关闭事件绑定(bind)到 window.open(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43276757/

相关文章:

javascript - Ajax 完成回调不等待不是函数

javascript - 使用 data html 属性加载不同的内容

html - jQuery 如果 hasClass 不起作用

javascript - 使用 onError 两次

php - JavaScript 无法正常运行,请快速查看以进行调试

javascript - javascript 中的 ASP.NET MVC 标签?

javascript - 如何在框架和边缘扩展内容脚本之间进行通信?

javascript - SAP OpenUI5 - AttachRequestCompleted 内的调用函数

javascript - 如何在 moment.js 中获取月份的简称?

javascript - 用 Div 替换 iframe((多个)下拉列表相关)