文書が開いたときにヘッダーを追加する

次のセクションでは、新しい文書または既存の文書を開いたときに文書ヘッダーを自動的に変更する Word アドインを開発する方法について説明します。 この特定のアドインは Word 用ですが、マニフェストと webpack.config.js ファイルの構成は Excel と PowerPoint で同じです。 このイベントベースのアクティブ化パターンの概要については、「 イベントを使用してアドインをアクティブ化する」を参照してください。

新しいアドインを作成する

Word アドインのクイック スタートに従って新しいアドインを作成しますが、そこで説明されている手順での変更点に注意してください。

  • アドインのみのマニフェストのガイダンスを使用します。 Microsoft 365 の統合マニフェストでは、このプロジェクトで使用される OnDocumentOpened イベントはまだサポートされていません。
  • 言語を選択するように求められたら、[ JavaScript] を選択します。

注:

このチュートリアルで説明されているサンプルの完成版については、サンプルの GitHub リポジトリの「Word 文書が開かれたときにアドインを使用して自動的にラベルを追加する」サンプルを参照してください。

マニフェストを構成する

イベント ベースのアドインを有効にするには、マニフェストの VersionOverridesV1_0 ノードで次の要素を構成する必要があります。 以下に示す新しいマークアップについて、次の点に注意してください。

  • OnDocumentOpened イベントを処理するコードは、Web 上の Word ではブラウザー ランタイムで実行されますが、Windows 上の Word では JavaScript のみのランタイムで実行されます。 このパターンを構成するために、ブラウザー ランタイムをプロジェクトの commands.html ファイルにポイントする Runtime 要素が追加されます。 この要素には、"javascript" 型をオーバーライドし、JavaScript のみのランタイムを commands.js ファイルにポイントするランタイムの子オーバーライド要素があります。 Office アドインのランタイムの詳細については、「 Office アドインのランタイム」を参照してください。
  • ExtensionPoint 要素では、xsi:typeLaunchEvent に設定されます。 これにより、アドインのイベント ベースのアクティブ化機能が有効になります。
  • <ExtensionPoint> 要素の SourceLocation 要素では、resid値は、HTML ファイルを参照する Runtime 要素の値と一致するように設定されます。
  • LaunchEvent 要素では、TypeOnDocumentOpened に設定され、FunctionName 属性はイベント ハンドラーの JavaScript 関数名に設定されます。
  • Resources セクションでは、JsRuntimeWord.Urlは Web アプリケーションの \public サブフォルダーに設定されます。 この URL は、 webpack.config.js ファイルで行う変更と合わせて、JavaScript のみのランタイムで実行される commands.js が、ブラウザー ランタイムを必要とするコードにバンドルされないようにします。 「 webpack.config.jsの設定 」を参照してください。

次のサンプル マニフェスト コードを使用して、プロジェクトを更新します。

  1. コード エディターで、作成したクイック スタート プロジェクトを開きます。

  2. プロジェクトのルートにある manifest.xml ファイルを開きます。

  3. <VersionOverrides> ノード全体 (open タグと close タグを含む) を選択し、次の XML に置き換えます。

      <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">
        <Hosts>
          <Host xsi:type="Document">
            <Runtimes>
              <Runtime resid="WebViewRuntime.Url">
                <Override type="javascript" resid="JsRuntimeWord.Url"/>
              </Runtime>
            </Runtimes>
            <DesktopFormFactor>
              <GetStarted>
                <Title resid="GetStarted.Title"/>
                <Description resid="GetStarted.Description"/>
                <LearnMoreUrl resid="GetStarted.LearnMoreUrl"/>
              </GetStarted>
              <FunctionFile resid="Commands.Url"/>
              <ExtensionPoint xsi:type="LaunchEvent">
                <LaunchEvents>
                  <LaunchEvent Type="OnDocumentOpened" FunctionName="changeHeader"></LaunchEvent>
                </LaunchEvents>
                <SourceLocation resid="WebViewRuntime.Url"/>
              </ExtensionPoint>
              <ExtensionPoint xsi:type="PrimaryCommandSurface">
                <OfficeTab id="TabHome">
                  <Group id="CommandsGroup">
                    <Label resid="CommandsGroup.Label"/>
                    <Icon>
                      <bt:Image size="16" resid="Icon.16x16"/>
                      <bt:Image size="32" resid="Icon.32x32"/>
                      <bt:Image size="80" resid="Icon.80x80"/>
                    </Icon>
                    <Control xsi:type="Button" id="TaskpaneButton">
                      <Label resid="TaskpaneButton.Label"/>
                      <Supertip>
                        <Title resid="TaskpaneButton.Label"/>
                        <Description resid="TaskpaneButton.Tooltip"/>
                      </Supertip>
                      <Icon>
                        <bt:Image size="16" resid="Icon.16x16"/>
                        <bt:Image size="32" resid="Icon.32x32"/>
                        <bt:Image size="80" resid="Icon.80x80"/>
                      </Icon>
                      <Action xsi:type="ShowTaskpane">
                        <TaskpaneId>ButtonId1</TaskpaneId>
                        <SourceLocation resid="Taskpane.Url"/>
                      </Action>
                    </Control>
                  </Group>
                </OfficeTab>
              </ExtensionPoint>
            </DesktopFormFactor>
          </Host>
        </Hosts>
        <Resources>
          <bt:Images>
            <bt:Image id="Icon.16x16" DefaultValue="https://localhost:3000/assets/icon-16.png"/>
            <bt:Image id="Icon.32x32" DefaultValue="https://localhost:3000/assets/icon-32.png"/>
            <bt:Image id="Icon.80x80" DefaultValue="https://localhost:3000/assets/icon-80.png"/>
          </bt:Images>
          <bt:Urls>
            <bt:Url id="GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812"/>
            <bt:Url id="Commands.Url" DefaultValue="https://localhost:3000/commands.html"/>
            <bt:Url id="Taskpane.Url" DefaultValue="https://localhost:3000/taskpane.html"/>
            <bt:Url id="WebViewRuntime.Url" DefaultValue="https://localhost:3000/commands.html"/>
            <bt:Url id="JsRuntimeWord.Url" DefaultValue="https://localhost:3000/public/commands.js"/>
          </bt:Urls>
          <bt:ShortStrings>
            <bt:String id="GetStarted.Title" DefaultValue="Get started with your sample add-in!"/>
            <bt:String id="CommandsGroup.Label" DefaultValue="Event-activated add-in"/>
            <bt:String id="TaskpaneButton.Label" DefaultValue="My add-in"/>
          </bt:ShortStrings>
          <bt:LongStrings>
            <bt:String id="GetStarted.Description" DefaultValue="Your sample add-in loaded successfully. Go to the HOME tab and click the 'Show Task Pane' button to get started."/>
            <bt:String id="TaskpaneButton.Tooltip" DefaultValue="Click to show the task pane"/>
          </bt:LongStrings>
        </Resources>
      </VersionOverrides>
    
  4. 変更内容を保存します。

イベント ハンドラを実装する

OnDocumentOpened イベントが発生したときにアドインが動作できるようにするには、JavaScript イベント ハンドラーを実装する必要があります。 このセクションでは、新しいドキュメントに "Public" ヘッダーを追加したり、既にコンテンツを含む既存のドキュメントに "Highly Confidential" ヘッダーを追加する changeHeader 関数を作成します。

  1. ./src/commands フォルダで、commands.jsという名前のファイルを開きます。

  2. commands.js の内容全体を次の JavaScript コードに置き換えます。

      /*
      * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
      * See LICENSE in the project root for license information.
      */
      /* global global, Office, self, window */
    
      Office.onReady(() => {
        // If needed, Office.js is ready to be called.
      });
    
      async function changeHeader(event) {
        await Word.run(async (context) => {
          const body = context.document.body;
          body.load("text");
          await context.sync();
    
          if (body.text.length === 0) {
          // For new or empty documents, make a "Public" header. 
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            const firstPageHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.firstPage);
            header.clear();
            firstPageHeader.clear();
    
            header.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            firstPageHeader.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            header.font.color = "#07641d";
            firstPageHeader.font.color = "#07641d";
            await context.sync();
          } else {
            // For existing documents, make a "Highly Confidential" header.
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            const firstPageHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.firstPage);
            header.clear();
            firstPageHeader.clear();
            header.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            firstPageHeader.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            header.font.color = "#f8334d";
            firstPageHeader.font.color = "#f8334d";
            await context.sync();
          }
        });
    
        // Calling event.completed is required. event.completed lets the platform know that processing has completed.
        event.completed();
      }
    
      async function paragraphChanged() {
        await Word.run(async (context) => {
          const results = context.document.body.search("110");
          results.load("length");
          await context.sync();
          if (results.items.length === 0) {
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            header.clear();
            header.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            const font = header.font;
            font.color = "#07641d";
    
            await context.sync();
          } else {
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            header.clear();
            header.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            const font = header.font;
            font.color = "#f8334d";
    
            await context.sync();
          }
        });
      }
    
      async function registerOnParagraphChanged(event) {
        await Word.run(async (context) => {
          let eventContext = context.document.onParagraphChanged.add(paragraphChanged);
          await context.sync();
        });
        // Calling event.completed is required. event.completed lets the platform know that processing has completed.
        event.completed();
      }
    
      Office.actions.associate("changeHeader", changeHeader);
      Office.actions.associate("registerOnParagraphChanged", registerOnParagraphChanged);
    
  3. 変更内容を保存します。

webpack.config.js の構成

ブラウザーと JavaScript 専用ランタイム用に JavaScript コードの個別のバンドルが作成されるように 、webpack.config.js ファイルを構成する必要があります。 次の手順に従います。

  1. 他のグローバル constが宣言されているファイルの先頭に次の行を追加します。

    const path = require("path");
    
  2. アドインのアイコンが Microsoft 365 管理 ポータルの統合アプリの一覧に表示されるようにするには、ファイルの下部近くにある devServer オブジェクトに次のプロパティを追加します。

    allowedHosts: "all",
    
  3. JavaScript のみのランタイムで実行される commands.js が、ブラウザー ランタイムを必要とするコードにバンドルされないようにするには、次の static プロパティを devServer オブジェクトに追加します。

    static: {
        directory: path.join(__dirname, "dist"),
        publicPath: "/public",
      },
    

    devServer オブジェクト全体が次のようになります。

    devServer: {
      allowedHosts: "all",
      static: {
        directory: path.join(__dirname, "dist"),
        publicPath: "/public",
      },
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      server: {
        type: "https",
        options: env.WEBPACK_BUILD || options.https !== undefined ? options.https : await getHttpsOptions(),
      },
      port: process.env.npm_package_config_dev_server_port || 3000,
    },
    

テスト用サンプルをインストールする

  1. コマンド プロンプトで、プロジェクトのルートに移動します。
  2. npm run build:dev を実行します。
  3. npm run dev-server を実行します。
  4. Microsoft 365 管理ポータルで、ナビゲーション ウィンドウの [ 設定 ] セクションを展開し、[ 統合アプリ] を選択します。
  5. [ 統合アプリ ] ページで、[ カスタム アプリのアップロード ] アクションを選択します。
  6. [展開するアプリをアップロード] ページで、[アプリの種類] ドロップダウンから [Office アドイン] を選択します。
  7. [ アプリのアップロード方法を選択する ] セクションで、[ デバイスからマニフェスト ファイル (.xml) をアップロード] を選択します。
  8. ファイル ピッカーを使用してプロジェクトのルートに移動し、 manifest.xml ファイルを選択します。
  9. [ユーザーとして 自分のみ ] を選択します。
  10. 画面の指示に従って展開を完了します。

重要

アドインは、プラットフォームに伝達されるまで実行できません。 Web 上の Word への伝達には数時間かかる場合があります。通常は 2 時間から 3 時間かかります。 Windows 上の Word への伝達には 24 時間かかる場合があります。通常は 6 時間から 12 時間です。

アドインが反映されたかどうかをテストするには、「 試してみる」を参照してください。

試してみる

  1. Web 上の Word または Windows 上の Word で、新規および既存の Word 文書の両方を開いてみてください。 アドインがプラットフォームに伝達された場合は、ドキュメントを開いたときにヘッダーが自動的に追加され、リボンの [ホーム] タブにイベントが有効化されたアドイン グループに [マイ アドイン] ボタンが表示されるはずです。 これらのことが起こらない場合は、プラットフォームへの伝達が完了していません。 Word を閉じて、しばらくしてからもう一度お試しください。
  2. [ 個人用アドイン ] ボタンを選択して作業ウィンドウを開きます。
  3. 作業ウィンドウでいずれかのリンクを選択して、ヘッダーを追加または変更します。

重要

サンプルの操作が終了したら、 アンインストールします

アドインをアンインストールする

アドインをアンインストールするには、次の手順を実行します。

  1. Microsoft 365 管理ポータルで、ナビゲーション ウィンドウの [ 設定 ] セクションを展開し、[ 統合アプリ] を選択します。
  2. [ 統合アプリ] ページで、アドインを選択します。
  3. アドインのポップアップで、[ アプリの削除] を選択します。
  4. [ アプリの削除 ] ページで、アプリを削除することを確認し、[ 削除] を選択します。
  5. [ 正常に削除されました] ページで、[ 完了] を選択します。

重要

アンインストールは、インストールの場合と同様にプラットフォームに伝達する必要があります。 Web 上の Word への伝達には数時間かかる場合があります。通常は 2 時間から 3 時間かかります。 Windows 上の Word への伝達には 24 時間かかる場合があります。通常は 6 時間から 12 時間です。

アンインストールが伝播されたかどうかをテストするには、プラットフォームで Word ファイルを開きます。 イベントがアクティブ化されたアドイン グループ内の [マイ アドイン] ボタンがリボンの [ホーム] タブにまだ表示されている場合は、伝播は行われていません。 Word を閉じて、しばらくしてからもう一度お試しください。

関連項目