您的位置:首页 > 其它

在网页中执行本地exe程序的两种方式

2013-12-19 16:37 295 查看
一、有时候,需要在 网页上去执行本地的一个EXE文件,如果用javascript ,一般浏览器,由于安全问题,都会禁止掉这个特性。但经过测试,目前在ie,firefox中仍然可以用JS来实现,但在chrome,safari
中没有实现。本文就用javascript在IE,FIREFOX中执行 exe 文件做例子。


程序代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title> IE 或 Firefox 执行 Exe 文件 </title>

<script>

function LaunchApp() {

var exepath="C:\\WINDOWS\\NOTEPAD.EXE";

if (!document.all) {

netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

var file = window.Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);

file.initWithPath(exepath);

var run = window.Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);

run.init(file);

var parameters = [""];

run.run(false, parameters,parameters.length);

}

else{

var ws = new ActiveXObject("WScript.Shell");

ws.Exec(exepath);

}

}

</script>

</head>

<body>

<input type="button" onclick="javascript:LaunchApp()" value="执行EXE" />

</body>

</html>

打开的文件是 notepad ,记事本,你可以替换成,你想要打开的文件。在 IE,FIREFOX 下通过。

使用这种方式打开 EXE,不是很方便,而且有局限

二、另外一种方法,就是 url protocol 的方式来实现。用这种方式实现,任何浏览器都兼容,不会存在只有前面那种只有IE或FIREFOX才行的情况。

都用过QQ,迅雷,电驴,在网页上点击的时候,就会弹出QQ,或者迅雷,电驴的下载界面,用的就是这个原理,在微软的MSDN上也有说明:http://msdn.microsoft.com/en-us/library/aa767914%28v=vs.85%29.aspx 在这里,做一个简单的例子。

1. 先注册URL PROTOCOL, 在windows 下就是注册表:

========================================================

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\myprotocol]

@="myprotocol Protocol"

"URL Protocol"=""

[HKEY_CLASSES_ROOT\myprotocol\DefaultIcon]

@="C:\\WINDOWS\\NOTEPAD.EXE"

[HKEY_CLASSES_ROOT\myprotocol\shell]

@=""

[HKEY_CLASSES_ROOT\myprotocol\shell\open]

@=""

[HKEY_CLASSES_ROOT\myprotocol\shell\open\command]

@="\"C:\\WINDOWS\\NOTEPAD.EXE\" "

======================================================

保存内容为 reg文件,然后执行,就加入注册表,注册了这个名字为myprotocol 的协议.

2. 写测试页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>

<div>

<a href="myprotocol://">

执行可执行文件

</a>

</div>

</body>

</html>

运行页面,点击链接,就能直接打开 notepad 。因为这里用的是写字板测试的,你可以在注册表中,改成其他任何你要的程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: