This commit is contained in:
Atterpac 2025-05-18 16:52:50 -04:00
commit 2134bc6e0d

View file

@ -0,0 +1,167 @@
---
title: Custom Protocol Schemes (Deep Linking)
description: Guide to implementing custom URL schemes for deep linking in Wails applications across macOS, Windows, and Linux.
---
import { Aside } from '@astrojs/starlight/components';
# Custom Protocol Schemes (Deep Linking)
Custom protocol schemes (also known as custom URL schemes or deep linking) allow your Wails application to be launched or brought to the foreground by clicking a URL with a scheme you define (e.g., `myapp://some/data`). This is useful for various purposes, such as:
- OAuth authentication flows.
- Inter-application communication.
- Launching your app with a specific context or to perform a particular action.
Wails provides a unified way to handle these custom URL invocations across macOS, Windows, and Linux through the `events.Common.ApplicationLaunchedWithUrl` event.
## Defining Your Protocols
First, you need to define the custom protocol schemes your application will use. This is done in your `wails.json` project configuration file. Wails reads this file during the build process (`wails build`) to configure the necessary platform-specific assets like `Info.plist` for macOS, NSIS installer scripts for Windows, and `.desktop` files for Linux.
**Example: `wails.json`**
```json title="wails.json"
{
"name": "My App",
"description": "An amazing Wails app!",
"info": {
"companyName": "My Company",
"productName": "My Product",
// ... other info fields ...
"protocols": [
{
"scheme": "myapp",
"description": "My Application Custom Protocol"
},
{
"scheme": "anotherprotocol",
"description": "Another protocol for specific actions"
}
]
}
// ... other wails.json fields ...
}
```
This `info.protocols` array is what Wails uses to generate the necessary entries in platform-specific files. For example, in template files, you might access this via a path like `{{.Info.Protocols}}`.
<Aside type="note">
While `application.Options` in your `main.go` is used for runtime application settings, the definition of custom protocols for build-time asset generation (like `Info.plist`, NSIS scripts, `.desktop` files) should be managed in `wails.json`.
</Aside>
## Handling the Event in Your Application
When your application is launched or activated via a custom URL, Wails emits an `events.Common.ApplicationLaunchedWithUrl` event. You can listen for this event and retrieve the URL that triggered the launch.
```go title="main.go"
import (
"log"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
)
func main() {
app := application.New(application.Options{
Name: "My App", // Ensure this matches relevant info from wails.json if needed
Description: "An amazing Wails app!",
// ... other runtime options ...
})
app.OnApplicationEvent(events.Common.ApplicationLaunchedWithUrl, func(e *application.ApplicationEvent) {
launchedURL := e.Context().URL() // Retrieve the URL from the event context
log.Printf("Application launched with URL: %s", launchedURL)
// TODO: Process the URL (e.g., navigate, perform action, etc.)
// Example: app.EmitEvent("frontend:ShowURL", launchedURL)
})
// ... rest of your main function ...
err := app.Run()
if err != nil {
log.Fatal(err)
}
}
```
<Aside type="note">
The `e.Context().URL()` method returns the full URL string that was used to launch the application (e.g., `myapp://some/data?param=value`).
</Aside>
## Platform-Specific Setup and Behavior
While Wails aims for a unified event, the underlying mechanism for custom protocol registration and URL delivery varies by operating system.
### macOS
- **Setup:** Wails automatically configures your application's `Info.plist` file during the build process. It adds `CFBundleURLTypes` entries based on the `info.protocols` defined in your `wails.json` file.
```xml title="Info.plist (excerpt generated by Wails)"
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>My Application Custom Protocol</string> <!-- From Protocol.Description in wails.json -->
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string> <!-- From Protocol.Scheme in wails.json -->
</array>
</dict>
<!-- ... other protocols ... -->
</array>
```
- **How it Works:** When a URL like `myapp://` is opened, macOS uses LaunchServices to find the application registered for that scheme and sends it an Apple Event (`kAEGetURL`). Wails intercepts this event and translates it into the common `events.Common.ApplicationLaunchedWithUrl` Wails event, providing the URL via `e.Context().URL()`.
### Windows
- **Setup:** Custom protocol schemes on Windows are registered in the Windows Registry. Wails facilitates this through its NSIS installer template.
- When you build your application with the `-nsis` flag, Wails uses the `v3/internal/commands/updatable_build_assets/windows/nsis/wails_tools.nsh.tmpl` file.
- This template contains macros like `CUSTOM_PROTOCOL_ASSOCIATE` and `wails.associateCustomProtocols` which use the `info.protocols` from your `wails.json` (passed as `{{.Info.Protocols}}` to the template) to create the necessary registry entries during installation.
```nsis title="wails_tools.nsh.tmpl (excerpt)"
!macro wails.associateCustomProtocols
; Create custom protocols associations
{{range .Info.Protocols}}
!insertmacro CUSTOM_PROTOCOL_ASSOCIATE "{{.Scheme}}" "{{.Description}}" "$INSTDIR\${PRODUCT_EXECUTABLE},0" "$INSTDIR\${PRODUCT_EXECUTABLE} $\"%1$\""
{{end}}
!macroend
```
- **How it Works:** The installer registers your application executable to be called with the URL as a command-line argument (`%1`). For example, `your_app.exe "myapp://some/data"`.
- The Wails runtime for Windows (`v3/pkg/application/application_windows.go`) has been updated to check `os.Args` upon startup. If it detects an argument that looks like a URL (e.g., `os.Args[1]` contains `"://"`), it now emits the `events.Common.ApplicationLaunchedWithUrl` event with this URL.
<Aside type="important">
For Windows, custom protocol schemes are typically only registered when your application is installed via an installer (like the one generated by Wails with NSIS). Running the bare executable might not have the schemes registered system-wide.
</Aside>
### Linux
- **Setup:** On Linux, custom protocol handling is typically managed via `.desktop` files and the MIME type system.
- Wails uses a `.desktop` file template (e.g., `v3/internal/commands/updatable_build_assets/linux/desktop.tmpl`) which is populated during the build using information from `wails.json`.
```desktop title="desktop.tmpl (excerpt)"
[Desktop Entry]
Name={{.ProductName}}
Exec=/usr/local/bin/{{.BinaryName}} %u
MimeType={{range $index, $protocol := .Info.Protocols}}x-scheme-handler/{{$protocol.Scheme}};{{end}}
```
The `Exec` line uses `%u` which gets replaced by the URL. The `MimeType` line registers your application as a handler for `x-scheme-handler/your-scheme` for each protocol defined in `wails.json` (via `{{.Info.Protocols}}`).
- When packaging for Linux (e.g., using `nfpm`), this `.desktop` file is installed to `/usr/share/applications/`.
- A `postinstall.sh` script (e.g., `v3/internal/commands/build_assets/linux/nfpm/scripts/postinstall.sh`) is used to update the system's application and MIME databases:
```sh title="postinstall.sh (excerpt)"
#!/bin/sh
update-desktop-database -q /usr/share/applications
update-mime-database -n /usr/share/mime
```
- **How it Works:** When a URL like `myapp://` is opened, the desktop environment uses the MIME database to find the associated `.desktop` file and executes the command specified in its `Exec` line, substituting `%u` with the URL. Your application receives this URL as a command-line argument.
- The Wails runtime for Linux (`v3/pkg/application/application_linux.go`) checks `os.Args` on startup. If it detects an argument that looks like a URL, it emits the `events.Common.ApplicationLaunchedWithUrl` event.
## Testing Your Custom Protocols
- **macOS:** Open Terminal and type `open "your-scheme://your/data"`.
- **Linux:** Open a terminal and type `xdg-open "your-scheme://your/data"` (requires `xdg-utils` to be installed and the app to be properly packaged and registered).
- **Windows:** After installation via NSIS:
- You can try running `start your-scheme://your/data` from Command Prompt or PowerShell.
- Create a simple HTML file with a link `<a href="your-scheme://your/data">Test Link</a>` and open it in a browser.
<Aside type="tip">
Always ensure your application is properly built and installed (especially for Windows and Linux) for the system to recognize the custom protocol schemes.
</Aside>
By following this guide, you can effectively use custom protocol schemes to enhance your Wails application's interactivity and integration with other applications or web services.