iframe just before unload event

35.8k views Asked by At

I need to capture an event which should be triggered just before the content of the iframe disappears.

I have been trying to accomplish something like this

$iframe = $('iframe');
$iframe.beforeunload(function () {
  debugger;
});

OR

$iframe = $('iframe');
$iframe.unload(function () {
  debugger;
});

I have even tried binding it to the iframe window itself without any luck

$iframe = $('iframe');
$iframe[0].contentWindow.onunload = function () {
  debugger;
};

None of these eventhandlers actually trigger for me

and I am quite confused why. To reload the iframe I use .reload() from outside the iframe and from within, maybe I need to use a different method?

1

There are 1 answers

1
Max On BEST ANSWER

Figured it out! I didn't know the contentWindow looses its reference after a reload.

$iframe.load(function () {
  $iframe[0].contentWindow.onbeforeunload = function () {
    debugger;
  };
});