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

跨Word/Excel/PowerPoint获取文件最后保存时间的Office JS API问询

Cross-Host Approach to Get Last Save Time in Office JavaScript Add-ins

Great question—you’re right that Word’s document.properties.lastSaveTime is a host-specific API that won’t work in Excel or PowerPoint. Let’s break down reliable, cross-host solutions to track when a file was last saved (and trigger your upload prompt logic):

1. Track Save Times Manually with Office Settings

Since there’s no universal Office.js API for last save time across all three hosts, one robust approach is to maintain your own timestamp using the cross-host Office.context.document.settings storage. Here’s how to implement it:

  • Capture save/upload events: Listen for the cross-host DocumentSaved event (works in Word, Excel, PowerPoint) to record the latest save time whenever the user saves the file. You can also capture your successful upload events to update this timestamp.

    // Add a handler for document save events
    Office.context.document.addHandlerAsync(
      Office.EventType.DocumentSaved,
      () => {
        // Store the current ISO timestamp in add-in settings
        const currentTime = new Date().toISOString();
        Office.context.document.settings.set('lastTrackedSaveTime', currentTime);
        // Persist the settings to make them available across sessions
        Office.context.document.settings.saveAsync();
      }
    );
    
    // Also update this timestamp when an upload succeeds
    function onUploadSuccess() {
      const currentTime = new Date().toISOString();
      Office.context.document.settings.set('lastTrackedSaveTime', currentTime);
      Office.context.document.settings.saveAsync();
    }
    
  • Check for changes: When you need to prompt the user, compare the stored timestamp with the file’s dirty state (Office.context.document.isDirty, a cross-host property that returns true if there are unsaved changes). If isDirty is true, or if you detect the file has been saved since your last tracked time, trigger the upload prompt.

2. Use Office REST APIs (Cloud-Hosted Files Only)

If your add-in targets files stored in OneDrive or SharePoint, you can retrieve the official last save time via Microsoft Graph or SharePoint REST APIs:

  • First, get the file’s unique identifier or URL using the cross-host getFilePropertiesAsync method:

    Office.context.document.getFilePropertiesAsync((result) => {
      if (result.status === Office.AsyncResultStatus.Succeeded) {
        const fileUrl = result.value.url;
        // Use this URL to call Microsoft Graph/SharePoint API for file properties
      }
    });
    
  • Then, call the Graph API endpoint (GET /drive/items/{item-id}) to fetch the lastModifiedDateTime property, which reflects the last save time. Note: This requires your add-in to have the appropriate permissions (e.g., Files.Read).

3. Host-Specific Fallbacks (Graceful Compatibility)

If you prefer to leverage native host APIs where available (instead of manual tracking), you can build a wrapper function that detects the current host and calls the corresponding property:

async function getLastSaveTime() {
  const host = Office.context.host;
  let lastSaveTime;

  switch (host) {
    case Office.HostType.Word:
      await Word.run(async (context) => {
        const props = context.document.properties;
        context.load(props, 'lastSaveTime');
        await context.sync();
        lastSaveTime = props.lastSaveTime;
      });
      break;
    case Office.HostType.Excel:
      await Excel.run(async (context) => {
        const props = context.workbook.properties;
        context.load(props, 'lastSavedTime');
        await context.sync();
        lastSaveTime = props.lastSavedTime;
      });
      break;
    case Office.HostType.PowerPoint:
      await PowerPoint.run(async (context) => {
        const props = context.presentation.properties;
        context.load(props, 'lastSavedTime');
        await context.sync();
        lastSaveTime = props.lastSavedTime;
      });
      break;
  }

  return lastSaveTime;
}

This approach gives you the native save time value where possible, with clear branching for each host.

Key Notes

  • The Office.context.document.isDirty property is your best cross-host quick check for unsaved changes—even if you can’t get the exact save time, this tells you if the file has been modified since the last save.
  • Manual tracking with Office.settings works for both local and cloud files, making it the most versatile option for cross-host scenarios.

内容的提问来源于stack exchange,提问作者John.W.Harding

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:10:43