You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Office 365 Outlook Add-In创建配置界面并在JS中调用设置

Building a Settings UI & Managing Configs for Your Outlook Add-in

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:

This integrates seamlessly with Outlook's UI, so users will find it intuitive.

  1. 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>
  1. 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.settings works 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:23:12