---
title: "Flex中捕获浏览器的前进、后退、刷新、关闭事件(转)"
author: "surpass_li"
date: "2010-02-27T19:05:02Z"
tags: ["Flash", "Flex", "HTML", "浏览器"]
categories: ["Web前端"]
slug: "flex"
draft: false
lastmod: "2010-02-27T19:05:02Z"
id: 604368
url: "https://surpass-li.iteye.com/blog/604368"
---

### [Flex中捕获浏览器的前进、后退、刷新、关闭事件](http://tj007-bo.iteye.com/blog/358609)

如果不希望用户点击浏览器的前进、后退、刷新、关闭等误操作，可以捕获这些事件，实际上是用js捕获window.onbeforeunload而已，如果你不希望通过修改html来达到这个效果，可以参考我的另一篇[从flex-ifram项目中看到的，在as中写js函数](http://tj007-bo.iteye.com/blog/315600) 中的代码，可以做到不需要修改flex编译成的html文件即可达到效果。而你只需要在你的mxml代码中加入如下内容即可：

Java代码 

01. import  flash.external.ExternalInterface;
02. private   static  var FUNCTION\_USEREXIT:String =
03. "document.insertScript = function () "  +
04. "{ "  +
05. "window.onbeforeunload = function() "  +
06. "{ "  +
07. "var flexObj = MyTest2.checkExit(); "  + //MyTest2是swf在html中object的id
08. "if(flexObj != \\"\\") "  +
09. "{ "  +
10. "return flexObj; "  +
11. "}else{ "  +
12. "return; "  +
13. "} "  +
14. "} "  +
15. "} " ;

```
import flash.external.ExternalInterface;
private static var FUNCTION_USEREXIT:String = 
	"document.insertScript = function () " +
	"{ " +
		"window.onbeforeunload = function() " +
		"{ " +
			"var flexObj = MyTest2.checkExit(); " +//MyTest2是swf在html中object的id
			"if(flexObj != \"\") " +
			"{ " +
				"return flexObj; " +
			"}else{ " +
				"return; " +
			"} " +
		"} " +
	"} ";
```

然后在Application的creationComplete方法中添加如下代码：

Java代码 

1. ExternalInterface.call(FUNCTION\_USEREXIT);
2. ExternalInterface.addCallback("checkExit" ,checkExit);
3. public  function checkExit():String {
4. var userExitStr:String = "你如果现在离开，则您的所有信息将失效！" ;
5. return  userExitStr;
6. }

```
ExternalInterface.call(FUNCTION_USEREXIT);
ExternalInterface.addCallback("checkExit",checkExit);
public function checkExit():String {
      var userExitStr:String = "你如果现在离开，则您的所有信息将失效！";
      return userExitStr;
}
```

这样就可以在不修改html的情况下达到你所希望的效果了。延展这个题目，我们所有和js打交道的代码其实都可以通过这个方式来将需要的js函数写入flex的源码中。