Track
Mouse Position Outside of Flash
or
Detect if
Mouse is Not Over Flash
with ActionScript 2 ONLY.
I've noticed quite a few folks who want to track the position of the
mouse outside of Flash's stage, or at least want to know if the
mouse has left the stage area. Adobe says that it can't be done, at least with a 100% pure Flash solution, since Flash does not get
mouse events outside of its focus.
Good news! It CAN be done, so long as the Flash appears in a browser that supports JavaScript, and you don't even need to add any JavaScript code to the page! We'll use ExternalInterface to do everything.
Here's proof! (IE Only, see below for other browsers)
And here's how to do it:
Code:
// Assumes you have a button called "testBtn" and a dynamic field called "testField"
import flash.external.ExternalInterface;
testBtn.onRelease = function() {
var flashObjectName:String = "MySwf";
var methodName:String = "ReportMouseLoc";
var instance:Object = null;
var method:Function = ExternalMouseLoc;
var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method);
function ExternalMouseLoc(MouseX, MouseY) {
testField.text = MouseX+":"+MouseY;
}
var nullCall = ExternalInterface.call("function(){document.onmousemove = function(){var e = arguments[0] || event;window['"+flashObjectName+"'].ReportMouseLoc(e.clientX,e.clientY )}}");
};
What I'm doing here is packing an anonymous function into the ExternalInterface.call() method, which is an undocumented feature. This function, in turn, contains a subfunction that contains a callback reference to an ActionScript function. The callback subfunction is force-fed into the page's Event Manager, where it will persist until you leave the page.
Here's the double-packed JS code, broken out for legibility:
Code:
function(){
document.onmousemove = function(){
var e = arguments[0] || event;
window['mySWF'].ReportMouseLoc(e.clientX,e.clientY )
}
}
- This snippet only works for IE. If there's enough interest I'll post a Netscape/Firefox version. It's easy; I'm just lazy.
- Remember to set "AllowScriptAccess" to "always" for the OBJECT/EMBED tag of your swf if you are trying this without a web server.
- The var flashObjectName in the example above should be set to the ID of the SWF as it appears in the OBJECT/EMBED.
If anybody knows how to make the swf aware of the OBJ/EMB ID that it's known as, please let me know.
Enjoy!