After adding an onbeforeunload event to an enterprise app recently, I noticed that the event would fire whenever the user clicked part of a flash swf. This was occuring even though the user was not leaving the page. In this article, I will show you what causes this and how to fix it.

The Cause

If you use ActionScript’s getURL() method, you will find that (obviously) it fires the onbeforeunload event. In our application, we were using an old technique to call JavaScript inside ActionScript: getURL("javascript:myfunction()");

Even though we were only using it to pass variables between the two languages, it was acting like we were going to another page. Our onbeforeunload event pops up a standard “are you sure you want to leave” message, so it was repeatedly popping up when using the flash movie.

The Solution

It’s time to update your ActionScript. Since its almost 2011, you should have no problem using AS3, right? You want to replace getURL() with ExternalInterface.call(). Other than that, just be sure to import the package at the top of the ActionScript.

  • import the package at the top- import flash.external.ExternalInterface;
  • replace getURL("javascript:myFunction()"); with ExternalInterface.call("myFunction()");

Beware

Historically, there have been various bugs while attempting to use AS2 with ExternalInterface. This affected the calling of methods, transmission of variables, and cross browser issues. Either update your code to ActionScript 3 or use at your own risk.