API Application
Gambaran Umum
Section titled “Gambaran Umum”Application adalah inti aplikasi Wails Anda. Mengelola window, service, event, dan menyediakan akses ke semua fitur platform.
Membuat Application
Section titled “Membuat Application”import "github.com/wailsapp/wails/v3/pkg/application"
app := application.New(application.Options{ Name: "My App", Description: "My awesome application", Services: []application.Service{ application.NewService(&MyService{}), },})Metode Inti
Section titled “Metode Inti”Memulai event loop aplikasi.
func (a *App) Run() errorContoh:
err := app.Run()if err != nil { log.Fatal(err)}Mengembalikan: Error jika startup gagal
Quit()
Section titled “Quit()”Menutup aplikasi dengan graceful.
func (a *App) Quit()Contoh:
// In a menu handlermenu.Add("Quit").OnClick(func(ctx *application.Context) { app.Quit()})Config()
Section titled “Config()”Mengembalikan konfigurasi aplikasi.
func (a *App) Config() OptionsContoh:
config := app.Config()fmt.Println("App name:", config.Name)Manajemen Window
Section titled “Manajemen Window”app.Window.New()
Section titled “app.Window.New()”Membuat webview window baru dengan opsi default.
func (wm *WindowManager) New() *WebviewWindowContoh:
window := app.Window.New()window.Show()app.Window.NewWithOptions()
Section titled “app.Window.NewWithOptions()”Membuat webview window baru dengan opsi kustom.
func (wm *WindowManager) NewWithOptions(options WebviewWindowOptions) *WebviewWindowContoh:
window := app.Window.NewWithOptions(application.WebviewWindowOptions{ Title: "My Window", Width: 800, Height: 600, BackgroundColour: application.NewRGB(255, 255, 255),})app.Window.GetByName()
Section titled “app.Window.GetByName()”Mendapatkan window berdasarkan namanya. Mengembalikan window dan apakah ditemukan.
func (wm *WindowManager) GetByName(name string) (Window, bool)Contoh:
if window, ok := app.Window.GetByName("main"); ok { window.Show()}app.Window.GetAll()
Section titled “app.Window.GetAll()”Mengembalikan semua window aplikasi.
func (wm *WindowManager) GetAll() []WindowContoh:
windows := app.Window.GetAll()for _, window := range windows { fmt.Println("Window:", window.Name())}Manager
Section titled “Manager”Application menyediakan akses ke berbagai manager melalui properti:
app.Window // Window managementapp.Menu // Menu managementapp.Dialog // Dialog managementapp.Event // Event managementapp.Clipboard // Clipboard operationsapp.Screen // Screen informationapp.SystemTray // System trayapp.Browser // Browser operationsapp.Env // Environment variablesapp.ContextMenu // Context-menu managementapp.KeyBinding // Global keyboard shortcutsapp.Logger // *slog.LoggerContoh Penggunaan
Section titled “Contoh Penggunaan”// Create windowwindow := app.Window.New()
// Show dialogapp.Dialog.Info().SetMessage("Hello!").Show()
// Copy to clipboardapp.Clipboard.SetText("Copied text")
// Get screensscreens := app.Screen.GetAll()Manajemen Service
Section titled “Manajemen Service”RegisterService()
Section titled “RegisterService()”Mendaftarkan service ke aplikasi.
func (a *App) RegisterService(service Service)RegisterService tidak mengembalikan nilai; error inisialisasi service muncul via kegagalan ServiceStartup selama app.Run().
Contoh:
type MyService struct { app *application.App}
func NewMyService(app *application.App) *MyService { return &MyService{app: app}}
// Register after app creationapp.RegisterService(application.NewService(NewMyService(app)))Manajemen Event
Section titled “Manajemen Event”app.Event.Emit()
Section titled “app.Event.Emit()”Memancarkan event kustom. Mengembalikan true jika hook membatalkan emit.
func (em *EventManager) Emit(name string, data ...any) boolContoh:
// Emit event with dataapp.Event.Emit("user-logged-in", map[string]interface{}{ "username": "john", "timestamp": time.Now(),})app.Event.On()
Section titled “app.Event.On()”Mendengarkan event kustom. Mengembalikan func() unsubscribe.
func (em *EventManager) On(name string, callback func(*CustomEvent)) func()Contoh:
app.Event.On("user-logged-in", func(e *application.CustomEvent) { data := e.Data.(map[string]interface{}) username := data["username"].(string) fmt.Println("User logged in:", username)})app.Event.OnApplicationEvent()
Section titled “app.Event.OnApplicationEvent()”Mendengarkan event siklus hidup aplikasi. Parameter eventType adalah events.ApplicationEventType (dari paket events).
func (em *EventManager) OnApplicationEvent( eventType events.ApplicationEventType, callback func(*ApplicationEvent),) func()Contoh:
import "github.com/wailsapp/wails/v3/pkg/events"
// Listen for app-startedapp.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(e *application.ApplicationEvent) { fmt.Println("Application started")})
// Application shutdown is NOT an event constant; register cleanup via:app.OnShutdown(func() { fmt.Println("Application shutting down")})Metode Dialog
Section titled “Metode Dialog”Dialog diakses melalui manager app.Dialog. Lihat API Dialog untuk referensi lengkap.
Dialog Pesan
Section titled “Dialog Pesan”// Information dialogapp.Dialog.Info(). SetTitle("Success"). SetMessage("Operation completed!"). Show()
// Error dialogapp.Dialog.Error(). SetTitle("Error"). SetMessage("Something went wrong."). Show()
// Warning dialogapp.Dialog.Warning(). SetTitle("Warning"). SetMessage("This action cannot be undone."). Show()Dialog Pertanyaan
Section titled “Dialog Pertanyaan”Dialog pertanyaan menggunakan callback tombol untuk menangani respons pengguna:
dialog := app.Dialog.Question(). SetTitle("Confirm"). SetMessage("Continue?")
yes := dialog.AddButton("Yes")yes.OnClick(func() { // Handle yes})
no := dialog.AddButton("No")no.OnClick(func() { // Handle no})
dialog.SetDefaultButton(yes)dialog.SetCancelButton(no)dialog.Show()Dialog File
Section titled “Dialog File”// Open file dialogpath, err := app.Dialog.OpenFile(). SetTitle("Select File"). AddFilter("Images", "*.png;*.jpg"). PromptForSingleSelection()
// Save file dialogpath, err := app.Dialog.SaveFile(). SetTitle("Save File"). SetFilename("document.pdf"). AddFilter("PDF", "*.pdf"). PromptForSingleSelection()
// Folder selection (use OpenFile with directory options)path, err := app.Dialog.OpenFile(). SetTitle("Select Folder"). CanChooseDirectories(true). CanChooseFiles(false). PromptForSingleSelection()Logger
Section titled “Logger”Aplikasi menyediakan structured logger:
app.Logger.Info("Message", "key", "value")app.Logger.Error("Error occurred", "error", err)app.Logger.Debug("Debug info")app.Logger.Warn("Warning message")Contoh:
func (s *MyService) ProcessData(data string) error { s.app.Logger.Info("Processing data", "length", len(data))
if err := process(data); err != nil { s.app.Logger.Error("Processing failed", "error", err) return err }
s.app.Logger.Info("Processing complete") return nil}Penanganan Raw Message
Section titled “Penanganan Raw Message”Untuk aplikasi yang memerlukan kontrol langsung tingkat rendah atas komunikasi frontend-ke-backend, Wails menyediakan opsi RawMessageHandler. Ini melewati sistem binding standar.
RawMessageHandler
Section titled “RawMessageHandler”RawMessageHandler adalah field pada application.Options, bukan metode. Runtime memanggilnya untuk setiap raw message yang dikirim dari frontend via System.invoke().
type Options struct { // ... other fields ... RawMessageHandler func(window Window, message string, originInfo *OriginInfo)}OriginInfo membawa Origin, TopOrigin, dan IsMainFrame (platform mengisi subset berbeda — lihat Panduan Raw Messages untuk matriks per platform).
Contoh:
app := application.New(application.Options{ Name: "My App", RawMessageHandler: func(window application.Window, message string, originInfo *application.OriginInfo) { // Handle the raw message fmt.Printf("Received from %s (%s): %s\n", window.Name(), originInfo.Origin, message)
// You can respond using events window.EmitEvent("response", processMessage(message)) },})Untuk detail selengkapnya, lihat Panduan Raw Messages.
Opsi Spesifik Platform
Section titled “Opsi Spesifik Platform”Opsi Windows
Section titled “Opsi Windows”Konfigurasi perilaku khusus Windows di level aplikasi:
app := application.New(application.Options{ Name: "My App", Windows: application.WindowsOptions{ // WebView2 browser flags (apply to ALL windows) EnabledFeatures: []string{"msWebView2EnableDraggableRegions"}, DisabledFeatures: []string{"msExperimentalFeature"}, AdditionalBrowserArgs: []string{"--remote-debugging-port=9222"},
// Other Windows options WndClass: "MyAppClass", WebviewUserDataPath: "", // Default: %APPDATA%\[BinaryName.exe] WebviewBrowserPath: "", // Default: system WebView2 DisableQuitOnLastWindowClosed: false, },})Flag Browser:
EnabledFeatures- Feature flag WebView2 untuk diaktifkanDisabledFeatures- Feature flag WebView2 untuk dinonaktifkanAdditionalBrowserArgs- Argumen command-line Chromium
Lihat Opsi Window - Opsi Windows Level Aplikasi untuk dokumentasi detail.
Opsi Mac
Section titled “Opsi Mac”app := application.New(application.Options{ Name: "My App", Mac: application.MacOptions{ ActivationPolicy: application.ActivationPolicyRegular, ApplicationShouldTerminateAfterLastWindowClosed: true, },})Opsi Linux
Section titled “Opsi Linux”app := application.New(application.Options{ Name: "My App", Linux: application.LinuxOptions{ ProgramName: "my-app", DisableQuitOnLastWindowClosed: false, },})Contoh Application Lengkap
Section titled “Contoh Application Lengkap”package main
import ( "github.com/wailsapp/wails/v3/pkg/application")
func main() { app := application.New(application.Options{ Name: "My Application", Description: "A demo application", Mac: application.MacOptions{ ApplicationShouldTerminateAfterLastWindowClosed: true, }, })
// Create main window window := app.Window.NewWithOptions(application.WebviewWindowOptions{ Title: "My App", Width: 1024, Height: 768, MinWidth: 800, MinHeight: 600, BackgroundColour: application.NewRGB(255, 255, 255), URL: "http://wails.localhost/", })
window.Center() window.Show()
app.Run()}