Javascript 如何检测弹出窗口关闭事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31513828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:47:32  来源:igfitidea点击:

How to detect popup window close event

javascriptfacebook-graph-api

提问by Chan

javascript

javascript

document.querySelector('#share').onclick = function () {
    var popup = window.open('http://www.facebook.com/sharer/sharer.php?u=http://www.google.com', '', "width=400, height=400");

    popup.onbeforeunload = function() {
        alert('unload');
    }

    return false;
};

HTML

HTML

<a id="share" href="#">share</a>

Two things:

两件事情:

  1. I want to do something after user finish the facebook share thing, if I share the page by open window the window will be auto close after everything is done, so I want to use beforeloadevent to imitate after sharing callback, but I can't get it when popup is closed.

  2. If user just turn off the window or cancel sharing will also trigger the event, so it's not the best solution, is there any facebook sharing successful callback api?

  1. 我想在用户完成 facebook 分享之后做一些事情,如果我通过打开的窗口分享页面,窗口将在一切完成后自动关闭,所以我想使用beforeload事件来模仿after sharing callback,但在弹出时我无法得到它关闭了。

  2. 如果用户只是关闭窗口或取消共享也会触发该事件,所以这不是最好的解决方案,是否有facebook共享成功回调api?

采纳答案by JavaScript

It does not work due to cross domain calls. To get the unload event you need to call a popup instead, which has the wanted url in an iframe.

由于跨域调用,它不起作用。要获得卸载事件,您需要调用一个弹出窗口,它在 iframe 中具有所需的 url。

document.querySelector('#share').onclick = function(){
    var popup = window.open('popup.html', '', "width=400, height=400");

    popup.onbeforeunload = function(){
        console.log('unload');
    }
};

popup.html

弹出窗口.html

<iframe src = 'http://www.facebook.com/sharer/sharer.php?u=http://www.google.com'></iframe>

回答by Lev Lukomsky

Solved this problem with setInterval:

解决了这个问题setInterval

document.querySelector('#share').onclick = function () {
    var popup = window.open('http://www.facebook.com/sharer/sharer.php?u=http://www.google.com', '', "width=400, height=400");

    var popupTick = setInterval(function() {
      if (popup.closed) {
        clearInterval(popupTick);
        console.log('window closed!');
      }
    }, 500);

    return false;
};

回答by Ivan Kerin

I've made a small javascript plugin for that functionality and without the limitation of same domain.

我为该功能制作了一个小型 javascript 插件,并且没有相同域的限制。

It has some more functionality, like ability to open the popup with a post and other small stuff.

它具有更多功能,例如能够打开带有帖子和其他小东西的弹出窗口。

Hope people looking for an answer find it useful.

希望寻找答案的人发现它有用。

https://github.com/enhancv/popup-tools

https://github.com/enhancv/popup-tools