(个人理解)js唤起应用程序都是通过注册表来实现的,部分应用程序在安装时会自动写入注册表生成特定的URL Procotol,但一般项目中,需要唤起的应用程序不一定支持。此时我们只能通过修改注册表,自定义.reg文件(桌面新建记事本,将后缀改为.reg保存即可)并执行,将其写入注册表中。但在自定义外部协议的时候,我们需要写入该应用程序的安装地址。如下:
问题来了,安装的时候可以安装到任何位置,如何知道安装路径呢。这时为了统一路径,我们换一种方式,如下:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\EaglEye]
@="URL:openFolder Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\EaglEye\DefaultIcon]
@="cmd.exe,1"
[HKEY_CLASSES_ROOT\EaglEye\shell]
[HKEY_CLASSES_ROOT\EaglEye\shell\open]
[HKEY_CLASSES_ROOT\EaglEye\shell\open\command]
@="cmd /c start C:\\Users\\Public\\Desktop\\宁夏植保4G图传 %1"
安装时默认生成桌面快捷方式,同过cmd打开桌面快捷方式来唤起。桌面快捷方式不出意外都在该文件夹下。
如何检测是否安装该应用呢,其实就是通过协议去检测该路径下是否该应用。检测方法如下(网上搜的,具体作者是谁不知~~~):
export function openUrlWithInputTimeoutHack(url, failCb, successCb) {
let target = document.createElement('input')
target.style.width = '0'
target.style.height = '0'
target.style.position = 'fixed'
target.style.top = '0'
target.style.left = '0'
document.body.appendChild(target)
target.focus();
var handler = _registerEvent(target, "blur", onBlur);
console.log('focus')
function onBlur() {
console.log('blur')
successCb && successCb()
handler.remove()
clearTimeout(timeout)
document.body.removeChild(target)
};
//will trigger onblur
location.href = url
// Note: timeout could vary as per the browser version, have a higher value
var timeout = setTimeout(function () {
console.log('setTimeout')
failCb && failCb()
handler.remove()
document.body.removeChild(target)
}, 1000);
}
function _registerEvent(target, eventType, cb) {
if (target.addEventListener) {
target.addEventListener(eventType, cb);
return {
remove: function () {
target.removeEventListener(eventType, cb);
}
};
} else {
target.attachEvent(eventType, cb);
return {
remove: function () {
target.detachEvent(eventType, cb);
}
};
}
}
在需要用到的页面引入该方法,具体调用如下:
import { openUrlWithInputTimeoutHack } from '@/utils/arouse'
openUrlWithInputTimeoutHack('EaglEye:\\', () => {
console.log('未安装');
window.location.href = 'xxx软件下载路径'
}, () => {
console.log('已安装,自动唤起');
})
EaglEye:\\ 就是我们在上面.reg文件中自定义的外部协议
此时,全部流程就走完了。有两个比较鸡肋的地方:1.自定义的.reg文件,需要手动运行。(也就是说,如果是客户使用的话,也得自己运行该文件)。2.安装软件的时候,必须生成桌面快捷方式。
该文章为个人理解,如有问题请见谅~~~~~~