前提:
项目需要,通过在浏览器地址栏输入对应的软件协议来唤起应用。
实现原理:
1.使用electron的setAsDefaultProtocolClient方法(扩展阅读:app | Electron)
app.setAsDefaultProtocolClient(protocol[, path, args])
protocol
string - The name of your protocol, without://
. For example, if you want your app to handleelectron://
links, call this method withelectron
as the parameter.path
string (optional) Windows - The path to the Electron executable. Defaults toprocess.execPath
args
string[] (optional) Windows - Arguments passed to the executable. Defaults to an empty arrayReturns
boolean
- Whether the call succeeded.Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with
your-protocol://
will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter.Note: On macOS, you can only register protocols that have been added to your app's
info.plist
, which cannot be modified at runtime. However, you can change the file during build time via Electron Forge, Electron Packager, or by editinginfo.plist
with a text editor. Please refer to Apple's documentation for details.Note: In a Windows Store environment (when packaged as an
appx
) this API will returntrue
for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must declare the protocol in your manifest.
// 应用主文件
public constructor(){
// ******
this.setAsDefaultProtocolClient();
// ******
}
private setAsDefaultProtocolClient () {
app.setAsDefaultProtocolClient(${protocol_string});
}
2.在应用安装模版中添加协议注册方法
; 注册 URL 协议
WriteRegStr HKCR "${PROTOCOL_STRING}" "" "URL:${PROTOCOL_STRING}"
WriteRegStr HKCR "${PROTOCOL_STRING}" "URL Protocol" ""
WriteRegStr HKCR "${PROTOCOL_STRING}\DefaultIcon" "" "$appExe,0"
WriteRegStr HKCR "${PROTOCOL_STRING}\shell" "" ""
WriteRegStr HKCR "${PROTOCOL_STRING}\shell\open" "" ""
WriteRegStr HKCR "${PROTOCOL_STRING}\shell\open\command" "" '"$appExe" "%1"'