22

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?

4
  • How about: $iframe = $('iframe')[0];
    – Lance
    Jun 8, 2015 at 20:58
  • Then: $iframe.contentWindow.onunload = function ...
    – Lance
    Jun 8, 2015 at 20:58
  • 1
    Hmm, this should be the equivalence: $iframe[0].contentWindow.onunload
    – Max
    Jun 8, 2015 at 21:00
  • Yes, you would think, but I've seen stupider things...
    – Lance
    Jun 8, 2015 at 21:06

1 Answer 1

38

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

$iframe.load(function () {
  $iframe[0].contentWindow.onbeforeunload = function () {
    debugger;
  };
});
1
  • 2
    On modern versions of jQuery (3.x) you'd need to change this to $iframe.on( 'load', function(){ ... } ); Nov 11, 2020 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.