如何为Office 365 Outlook Add-In创建配置界面并在JS中调用设置
Hey there! Let's walk through how to create a settings interface for your cross-platform Outlook add-in (desktop + web) and how to use those settings in your JavaScript code. This is a common need, and Office.js has built-in tools to make it straightforward.
Part 1: Creating the Settings UI
You have two solid options here—using the native Office Settings Pane (integrated directly into Outlook) or building a custom task pane for settings. Let's cover both:
Option 1: Use the Native Settings Pane (Recommended)
This integrates seamlessly with Outlook's UI, so users will find it intuitive.
- Update your manifest.xml
Add an extension point for the settings pane to your manifest. This tells Outlook where to find your settings page:
<VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0"> <Hosts> <Host xsi:type="MailHost"> <DesktopFormFactor> <!-- Add this ExtensionPoint block --> <ExtensionPoint xsi:type="SettingsTaskPane"> <SourceLocation resid="SettingsPageUrl"/> <Label resid="SettingsPaneLabel"/> </ExtensionPoint> <!-- ... other extension points (like MessageReadCommandSurface) ... --> </DesktopFormFactor> </Host> </Hosts> <Resources> <bt:Urls> <bt:Url id="SettingsPageUrl" DefaultValue="https://your-add-in-domain.com/settings.html"/> </bt:Urls> <bt:ShortStrings> <bt:String id="SettingsPaneLabel" DefaultValue="My Add-in Settings"/> </bt:ShortStrings> </Resources> </VersionOverrides>
- Build the settings.html page
Create a simple HTML form with inputs for company ID, username, and a save button:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Add-in Settings</title> <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script> </head> <body> <div style="padding: 20px;"> <h3>My Add-in Configuration</h3> <div> <label for="companyId">Company ID:</label> <input type="text" id="companyId" style="margin: 8px 0; padding: 4px; width: 100%;"> </div> <div> <label for="username">Username:</label> <input type="text" id="username" style="margin: 8px 0; padding: 4px; width: 100%;"> </div> <button id="saveBtn" style="padding: 8px 16px; background: #0078d4; color: white; border: none; border-radius: 4px;">Save Settings</button> </div> <script src="settings.js"></script> </body> </html>
Option 2: Custom Task Pane for Settings
If you want more control over the UI (like adding tabs or advanced features), you can create a dedicated task pane for settings. Just add a button to your add-in's command bar that opens this task pane using Office.context.ui.displayDialogAsync() or a separate task pane entry in the manifest.
Part 2: Storing & Using Settings in JavaScript
Office.js provides the Office.context.settings object—this is designed specifically for storing add-in settings, and it syncs across Outlook desktop and web for the same user. Perfect for your use case!
Saving Settings
In your settings.js file, add logic to save the user's input when they click the save button:
Office.onReady(() => { // Wait for Office to initialize before attaching events document.getElementById('saveBtn').addEventListener('click', async () => { const companyId = document.getElementById('companyId').value.trim(); const username = document.getElementById('username').value.trim(); if (!companyId || !username) { alert('Please fill in both fields!'); return; } // Store the settings Office.context.settings.set('companyId', companyId); Office.context.settings.set('username', username); try { // Persist the settings to the cloud/Outlook await new Promise((resolve, reject) => { Office.context.settings.saveAsync((result) => { if (result.status === Office.AsyncResultStatus.Succeeded) { resolve(); } else { reject(result.error); } }); }); alert('Settings saved successfully!'); // Close the settings pane if needed Office.context.ui.closeContainer(); } catch (error) { console.error('Error saving settings:', error); alert('Failed to save settings. Please try again.'); } }); // Pre-fill inputs with existing settings on load const savedCompanyId = Office.context.settings.get('companyId'); const savedUsername = Office.context.settings.get('username'); if (savedCompanyId) document.getElementById('companyId').value = savedCompanyId; if (savedUsername) document.getElementById('username').value = savedUsername; });
Reading & Using Settings in Your Main Add-in Code
In your main task pane or command logic, retrieve the settings and pass them to your remote service:
Office.onReady(async () => { // Get saved settings const companyId = Office.context.settings.get('companyId'); const username = Office.context.settings.get('username'); if (!companyId || !username) { // Prompt user to configure settings if they're missing alert('Please configure your add-in settings first.'); // Optionally open the settings pane automatically Office.context.ui.displayDialogAsync('https://your-add-in-domain.com/settings.html', { height: 400, width: 300, displayInIframe: true }); return; } // Pass settings to your remote service try { const response = await fetch('https://your-remote-service.com/api/process', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ companyId: companyId, username: username }) }); if (response.ok) { console.log('Settings sent to remote service successfully'); // Handle success (e.g., update UI) } else { console.error('Failed to send settings to remote service'); } } catch (error) { console.error('Network error:', error); } });
Key Notes
- Cross-platform compatibility:
Office.context.settingsworks the same way in Outlook desktop (Windows/Mac) and web—no extra code needed. - User-specific storage: Settings are tied to the user's Office 365 account, so they'll see the same settings across all devices.
- Async operations: Always use
saveAsync(not synchronous calls) because settings are persisted to the cloud.
内容的提问来源于stack exchange,提问作者Naupad Doshi

