创建字典任务窗格加载项

本文介绍任务窗格加载项的示例,其中包含一个随附的 Web 服务,该服务为用户在Word文档中的当前选择提供字典定义或同义词库同义词。

字典 Office 外接程序基于标准任务窗格外接程序,它具有附加功能来支持在 Office 应用程序的 UI 中的其他位置查询和显示字典 XML Web 服务的定义。

在典型的字典任务窗格加载项中,用户在文档中选择某字词或短语,加载项依据的 JavaScript 逻辑将此选定内容传递给字典提供程序的 XML Web 服务。 然后,字典提供程序的网页更新为,向用户显示选定内容的定义。

XML Web 服务组件以示例 OfficeDefinitions XML 架构定义的格式返回最多三个定义,这些定义随后在托管 Office 应用程序的 UI 中的其他位置向用户显示。

图 1 显示了在 Word 中运行的必应品牌字典加载项的选择和显示体验。

图 1. 显示选定字词的定义的字典加载项

显示定义的字典应用。

由你确定在字典加载项的 HTML UI 中选择“ 查看更多 ”链接是否在任务窗格中显示更多信息,还是打开一个指向所选字词或短语的完整网页的单独窗口。

图 2 显示了上下文菜单中的 Define 命令,该命令使用户能够快速启动已安装的字典。 图 3 到图 5 显示了 Office UI 中用于提供Word中的定义的字典 XML 服务的位置。

图 2. 在上下文菜单中定义命令

定义上下文菜单。

图 3. “拼写和语法”窗格中的定义

“拼写和语法”窗格中的定义。

图 4. “同义词库”窗格中的定义

“同义词库”窗格中的定义。

图 5. “阅读模式”中的定义

阅读模式下的定义。

若要创建提供字典查找的任务窗格加载项,请创建两个main组件。

  • XML Web 服务,该服务从字典服务中查找定义,然后以字典加载项可以使用和显示的 XML 格式返回这些值。
  • 任务窗格加载项,它将用户的当前选择提交至字典 Web 服务,显示定义,还可以选择将这些值插入文档。

以下各节提供了有关如何创建这些组件的示例。

先决条件

  • 已安装 Office/SharePoint 开发 工作负载的 Visual Studio 2019 或更高版本

    注意

    如果之前已安装 Visual Studio,请 使用 Visual Studio 安装程序,以确保安装 Office/SharePoint 开发 工作负载。

  • 已连接到 Microsoft 365 订阅的 Office (包括 Office 网页版)。

接下来,在 Visual Studio 中创建Word外接程序项目。

  1. 在 Visual Studio 中,选择“新建项目”。

  2. 使用搜索框,输入外接程序。 选择“Word Web 外接程序”,然后选择“下一步”。

  3. 对项目命名,然后选择“创建”。

  4. 此时,Visual Studio 创建解决方案,且它的两个项目显示在“解决方案资源管理器”中。 Home.html 文件将在 Visual Studio 中打开。

若要详细了解Word加载项解决方案中的项目,请参阅快速入门

创建字典 XML Web 服务

XML Web 服务必须将对 Web 服务的查询作为符合 OfficeDefinitions XML 架构的 XML 返回。 以下两节介绍了 OfficeDefinitions XML 架构,并提供有关如何对返回该 XML 格式查询的 XML Web 服务编码的示例。

OfficeDefinitions XML 架构

以下代码显示了 OfficeDefinitions XML 架构示例的示例 XSD。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xs="https://www.w3.org/2001/XMLSchema"
  targetNamespace="http://schemas.microsoft.com/contoso/OfficeDefinitions"
  xmlns="http://schemas.microsoft.com/contoso/OfficeDefinitions">
  <xs:element name="Result">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="SeeMoreURL" type="xs:anyURI"/>
        <xs:element name="Definitions" type="DefinitionListType"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="DefinitionListType">
    <xs:sequence>
      <xs:element name="Definition" maxOccurs="3">
        <xs:simpleType>
          <xs:restriction base="xs:normalizedString">
            <xs:maxLength value="400"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

返回的 XML 由根 <Result> 元素组成,该元素包含具有零到三<个 Definition 子元素的 Definitions>>元素。< 每个子元素都包含最多 400 个字符的定义。 此外,必须在 SeeMoreURL> 元素中提供字典网站上完整页面的< URL。 以下示例演示返回的符合 OfficeDefinitions 架构的 XML 的结构。

<?xml version="1.0" encoding="utf-8"?>
<Result xmlns="http://schemas.microsoft.com/contoso/OfficeDefinitions">
  <SeeMoreURL xmlns="">https://www.bing.com/search?q=example</SeeMoreURL>
  <Definitions xmlns="">
    <Definition>Definition1</Definition>
    <Definition>Definition2</Definition>
    <Definition>Definition3</Definition>
  </Definitions>
 </Result>

示例字典 XML Web 服务

以下 C# 代码提供了一个示例,说明如何为以 OfficeDefinitions XML 格式返回字典查询结果的 XML Web 服务编写代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Text;
using System.IO;
using System.Net;
using System.Web.Script.Services;

/// <summary>
/// Summary description for _Default.
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this web service to be called from script, using ASP.NET AJAX, include the following line. 
[ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        // Uncomment the following line if using designed components.
        // InitializeComponent(); 
    }

    // You can replace this method entirely with your own method that gets definitions
    // from your data source and then formats it into the example OfficeDefinitions XML format. 
    // If you need a reference for constructing the returned XML, you can use this example as a basis.
    [WebMethod]
    public XmlDocument Define(string word)
    {

        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        {
            writer.WriteStartDocument();
            
                writer.WriteStartElement("Result", "http://schemas.microsoft.com/contoso/OfficeDefinitions");

                    // See More URL should be changed to the dictionary publisher's page for that word on
                    // their website.
                    writer.WriteElementString("SeeMoreURL", "https://www.bing.com/search?q=" + word);

                    writer.WriteStartElement("Definitions");
            
                        writer.WriteElementString("Definition", "Definition 1 of " + word);
                        writer.WriteElementString("Definition", "Definition 2 of " + word);
                        writer.WriteElementString("Definition", "Definition 3 of " + word);
                   
                    writer.WriteEndElement(); // End of Definitions element.

                writer.WriteEndElement(); // End of Result element.
            
            writer.WriteEndDocument();
        }
        writer.Close();

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());

        return doc;
    }
}

若要开始开发,可以执行以下操作。

创建 Web 服务

  1. 在 Visual Studio 中将 Web 服务 (ASMX) 添加到外接程序的 Web 应用程序项目,并将其命名为 DictionaryWebService
  2. 将关联的 .asmx.cs 文件的全部内容替换为前面的 C# 代码示例。

更新 Web 服务标记

  1. 解决方案资源管理器,选择 DictionaryWebService.asmx 文件,然后打开其上下文菜单并选择“查看标记”。

  2. 将 DictionaryWebService.asmx 的内容替换为以下代码。

    <%@ WebService Language="C#" CodeBehind="DictionaryWebService.asmx.cs" Class="WebService" %>
    

更新 web.config

  1. 在外接程序的 Web 应用程序项目的 Web.config 中,将以下内容添加到 <system.web> 节点。

    <webServices>
      <protocols>
        <add name="HttpGet" />
        <add name="HttpPost" />
      </protocols>
    </webServices>
    
  2. 保存所做的更改。

字典加载项的组件

字典加载项包含三个主要组件文件:

  • 描述加载项的 XML 清单文件。
  • 提供加载项 UI 的 HTML 文件。
  • JavaScript 文件,用于提供从文档中获取用户选择的逻辑,将选择作为查询发送给 Web 服务,然后在外接程序的 UI 中显示返回的结果。

字典加载项的清单文件示例

下面是字典加载项的示例清单文件。

<?xml version="1.0" encoding="utf-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:type="TaskPaneApp">
  <Id>7164e750-dc86-49c0-b548-1bac57abdc7c</Id>
  <Version>15.0</Version>
  <ProviderName>Microsoft Office Demo Dictionary</ProviderName>
  <DefaultLocale>en-us</DefaultLocale>
  <!--DisplayName is the name that will appear in the user's list of applications.-->
  <DisplayName DefaultValue="Microsoft Office Demo Dictionary" />
  <!--Description is a 2-3 sentence description of this dictionary. -->
  <Description DefaultValue="The Microsoft Office Demo Dictionary is an example built to demonstrate how a
    publisher can create a dictionary that integrates with Office. It doesn't return real definitions." />
  <!--IconUrl is the URI for the icon that will appear in the user's list of applications.-->
  <IconUrl DefaultValue="http://contoso/_layouts/images/general/office_logo.jpg" />
  <SupportUrl DefaultValue="[Insert the URL of a page that provides support information for the app]" />
  <!--Hosts specifies the kind of Office application your dictionary add-in will support.
      You shouldn't have to modify this area.-->
  <Hosts>
    <Host Name="Document"/>
  </Hosts>
  <DefaultSettings>
    <!--SourceLocation is the URL for your dictionary.-->
    <SourceLocation DefaultValue="http://contoso/ExampleDictionary/DictionaryHome.html" />
  </DefaultSettings>
  <!--Permissions is the set of permissions a user will have to give your dictionary.
      If you need write access, such as to allow a user to replace the highlighted word with a synonym,
      use ReadWriteDocument. -->
  <Permissions>ReadDocument</Permissions>
  <Dictionary>
    <!--TargetDialects is the set of regional languages your dictionary contains. For example, if your
        dictionary applies to Spanish (Mexico) and Spanish (Peru), but not Spanish (Spain), you can specify
        that here. Do not put more than one language (for example, Spanish and English) here. Publish
        separate languages as separate dictionaries. -->
    <TargetDialects>
      <TargetDialect>EN-AU</TargetDialect>
      <TargetDialect>EN-BZ</TargetDialect>
      <TargetDialect>EN-CA</TargetDialect>
      <TargetDialect>EN-029</TargetDialect>
      <TargetDialect>EN-HK</TargetDialect>
      <TargetDialect>EN-IN</TargetDialect>
      <TargetDialect>EN-ID</TargetDialect>
      <TargetDialect>EN-IE</TargetDialect>
      <TargetDialect>EN-JM</TargetDialect>
      <TargetDialect>EN-MY</TargetDialect>
      <TargetDialect>EN-NZ</TargetDialect>
      <TargetDialect>EN-PH</TargetDialect>
      <TargetDialect>EN-SG</TargetDialect>
      <TargetDialect>EN-ZA</TargetDialect>
      <TargetDialect>EN-TT</TargetDialect>
      <TargetDialect>EN-GB</TargetDialect>
      <TargetDialect>EN-US</TargetDialect>
      <TargetDialect>EN-ZW</TargetDialect>
    </TargetDialects>
    <!--QueryUri is the address of this dictionary's XML web service (which is used to put definitions in
        additional contexts, such as the spelling checker.)-->
    <QueryUri DefaultValue="http://contoso/ExampleDictionary/WebService.asmx/Define?word="/>
    <!--Citation Text, Dictionary Name, and Dictionary Home Page will be combined to form the citation line
        (for example, this would produce "Examples by: Contoso",
        where "Contoso" is a hyperlink to http://www.contoso.com).-->
    <CitationText DefaultValue="Examples by: " />
    <DictionaryName DefaultValue="Contoso" />
    <DictionaryHomePage DefaultValue="http://www.contoso.com" />
  </Dictionary>
</OfficeApp>

以下各节介绍了特定于创建字典加载项清单文件的 Dictionary> 元素及其子元素。< 有关清单文件中的其他元素的信息,请参阅 Office 外接程序 XML 清单

Dictionary 元素

指定用于字典外接程序的设置。

父元素

<OfficeApp>

子元素

<TargetDialects><QueryUri><CitationText><Name><DictionaryHomePage>

备注

创建字典加载项时,Dictionary> 元素及其子元素将添加到任务窗格外接程序的清单中。<

TargetDialects 元素

指定此字典支持的区域语言集。 对于字典加载项,此为必需元素。

父元素

<Dictionary>

子元素

<TargetDialect>

备注

<TargetDialects> 元素及其子元素指定字典包含的区域语言集。 例如,如果字典同时适用于西班牙语(墨西哥)和西班牙语(秘鲁),但不适用于西班牙语(西班牙),可以在此元素中进行指定。 请勿在此清单中指定多种语言(例如,西班牙语和英语)。 请将各种语言发布为单独的字典。

示例

<TargetDialects>
  <TargetDialect>EN-AU</TargetDialect>
  <TargetDialect>EN-BZ</TargetDialect>
  <TargetDialect>EN-CA</TargetDialect>
  <TargetDialect>EN-029</TargetDialect>
  <TargetDialect>EN-HK</TargetDialect>
  <TargetDialect>EN-IN</TargetDialect>
  <TargetDialect>EN-ID</TargetDialect>
  <TargetDialect>EN-IE</TargetDialect>
  <TargetDialect>EN-JM</TargetDialect>
  <TargetDialect>EN-MY</TargetDialect>
  <TargetDialect>EN-NZ</TargetDialect>
  <TargetDialect>EN-PH</TargetDialect>
  <TargetDialect>EN-SG</TargetDialect>
  <TargetDialect>EN-ZA</TargetDialect>
  <TargetDialect>EN-TT</TargetDialect>
  <TargetDialect>EN-GB</TargetDialect>
  <TargetDialect>EN-US</TargetDialect>
  <TargetDialect>EN-ZW</TargetDialect>
</TargetDialects>

TargetDialect 元素

指定此字典支持的一种区域语言。 对于字典加载项,此为必需元素。

父元素

<TargetDialects>

备注

以 RFC1766 language 标记格式指定区域语言的值,例如 EN-US。

示例

<TargetDialect>EN-US</TargetDialect>

QueryUri 元素

指定词典查询服务的终结点。 对于字典加载项,此为必需元素。

父元素

<Dictionary>

备注

这是字典提供程序的 XML Web 服务的 URI。 被正确转义的查询将被追加到此 URI。

示例

<QueryUri DefaultValue="http://msranlc-lingo1/proof.aspx?q="/>

CitationText 元素

指定引文中要使用的文本。 对于字典加载项,此为必需元素。

父元素

<Dictionary>

备注

此元素指定将在从 Web 服务返回的内容之下的行中显示的引文文本的开头(例如,“Results by:”或“Powered by:”)。

对于此元素,可以使用 Override> 元素为其他区域设置<指定值。 例如,如果用户正在运行 Office 的西班牙语 SKU,但使用的是英语字典,则允许引文行读取“Resultados por: Bing”,而不是“Results by: Bing”。 有关如何为其他区域设置指定值的详细信息,请参阅 本地化

示例

<CitationText DefaultValue="Results by: " />

DictionaryName 元素

指定该词典的名称。 对于字典加载项,此为必需元素。

父元素

<Dictionary>

备注

此元素指定引文文本中的链接文本。 引文文本显示在从 Web 服务返回的内容之下的行中。

对于此元素,可以指定其他区域设置的值。

示例

<DictionaryName DefaultValue="Bing Dictionary" />

DictionaryHomePage 元素

指定该词典的主页的 URL。 对于字典加载项,此为必需元素。

父元素

<Dictionary>

备注

此元素指定引文文本中的链接 URL。 引文文本显示在从 Web 服务返回的内容之下的行中。

对于此元素,可以指定其他区域设置的值。

示例

<DictionaryHomePage DefaultValue="https://www.bing.com" />

更新字典加载项的清单文件

  1. 打开加载项项目中的 XML 清单文件。

  2. 使用名称更新 ProviderName> 元素的值<

  3. DisplayName> 元素的 DefaultValue 属性的值<替换为适当的名称,例如“Microsoft Office 演示词典”。><

  4. Description> 元素的 DefaultValue 属性的值<替换为相应的说明,例如,“Microsoft Office 演示词典是一个示例,用于演示发布者如何创建与 Office 集成的字典。>< 它不返回实际定义。”。

  5. “权限”>节点后面<添加以下代码,将“contoso”引用替换为你自己的公司名称,然后保存所做的更改。

    <Dictionary>
      <!--TargetDialects is the set of regional languages your dictionary contains. For example, if your
          dictionary applies to Spanish (Mexico) and Spanish (Peru), but not Spanish (Spain), you can
          specify that here. Do not put more than one language (for example, Spanish and English) here.
          Publish separate languages as separate dictionaries. -->
      <TargetDialects>
        <TargetDialect>EN-AU</TargetDialect>
        <TargetDialect>EN-BZ</TargetDialect>
        <TargetDialect>EN-CA</TargetDialect>
        <TargetDialect>EN-029</TargetDialect>
        <TargetDialect>EN-HK</TargetDialect>
        <TargetDialect>EN-IN</TargetDialect>
        <TargetDialect>EN-ID</TargetDialect>
        <TargetDialect>EN-IE</TargetDialect>
        <TargetDialect>EN-JM</TargetDialect>
        <TargetDialect>EN-MY</TargetDialect>
        <TargetDialect>EN-NZ</TargetDialect>
        <TargetDialect>EN-PH</TargetDialect>
        <TargetDialect>EN-SG</TargetDialect>
        <TargetDialect>EN-ZA</TargetDialect>
        <TargetDialect>EN-TT</TargetDialect>
        <TargetDialect>EN-GB</TargetDialect>
        <TargetDialect>EN-US</TargetDialect>
        <TargetDialect>EN-ZW</TargetDialect>
      </TargetDialects>
      <!--QueryUri is the address of this dictionary's XML web service (which is used to put definitions in
          additional contexts, such as the spelling checker.)-->
      <QueryUri DefaultValue="~remoteAppUrl/DictionaryWebService.asmx"/>
      <!--Citation Text, Dictionary Name, and Dictionary Home Page will be combined to form the citation
          line (for example, this would produce "Examples by: Contoso", where "Contoso" is a hyperlink to
          http://www.contoso.com).-->
      <CitationText DefaultValue="Examples by: " />
      <DictionaryName DefaultValue="Contoso" />
      <DictionaryHomePage DefaultValue="http://www.contoso.com" />
    </Dictionary>
    

创建字典加载项的 HTML 用户界面

以下两个示例演示用于演示字典外接程序的 UI 的 HTML 和 CSS 文件。 若要查看 UI 在外接程序的任务窗格中如何显示,请参阅代码之后的图 6。 若要了解 JavaScript 的实现如何为此 HTML UI 提供编程逻辑,请参阅紧跟本部分后面的 编写 JavaScript 实现

在 Visual Studio 中外接程序的 Web 应用程序项目中,可以将 ./Home.html 文件的内容替换为以下示例 HTML。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

    <!--The title will not be shown but is supplied to ensure valid HTML.-->
    <title>Example Dictionary</title>

    <!--Required library includes.-->
    <script type="text/javascript" src="https://ajax.microsoft.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>

    <!--Optional library includes.-->
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>

    <!--App-specific CSS and JS.-->
    <link rel="Stylesheet" type="text/css" href="Home.css" />
    <script type="text/javascript" src="Home.js"></script>
</head>

<body>
    <div id="mainContainer">
        <div>INSTRUCTIONS</div>
        <ol>
            <li>Ensure there's text in the document.</li>
            <li>Select text.</li>
        </ol>
        <div id="header">
            <span id="headword"></span>
        </div>
        <div>DEFINITIONS</div>
        <ol id="definitions">
        </ol>
        <div id="SeeMore">
            <a id="SeeMoreLink" target="_blank">See More...</a>
        </div>
        <div id="message"></div>
    </div>
</body>

</html>

以下示例显示了 .css 文件的内容。

在 Visual Studio 中外接程序的 Web 应用程序项目中,可以将 ./Home.css 文件的内容替换为以下示例 CSS。

#mainContainer
{
    font-family: Segoe UI;
    font-size: 11pt;
}

#headword
{
    font-family: Segoe UI Semibold;
    color: #262626;
}

#definitions
{
    font-size: 8.5pt;
}
a
{
    font-size: 8pt;
    color: #336699;
    text-decoration: none;
}
a:visited
{
    color: #993366;
}
a:hover, a:active
{  
    text-decoration: underline;
}

图 6. 演示字典 UI

演示字典 UI。

编写 JavaScript 实现

以下示例显示了 .js 文件中的 JavaScript 实现,该文件从加载项的 HTML 页调用,为演示字典加载项提供编程逻辑。 此脚本使用前面所述的 XML Web 服务。 脚本作为示例 Web 服务被置于同一目录中时将从该服务获取定义。 通过修改 xmlServiceURL 文件顶部的 变量,可以将其与符合 OfficeDefinitions 的公共 XML Web 服务一起使用。

从此实现调用的 Office JavaScript API (Office.js) 的主要成员显示在以下列表中。

  • 对象的 initialize 事件,该事件 Office 在初始化外接程序上下文时引发,并提供对代表外接程序与之交互的文档 的 Document 对象实例的访问权限。
  • 对象的 addHandlerAsync 方法 Document ,在 函数中 initialize 调用该方法,为文档的 SelectionChanged 事件添加事件处理程序,以侦听用户选择更改。
  • 对象的 getSelectedDataAsync 方法Document,在引发事件处理程序以获取用户选择的单词或短语时SelectionChanged,在函数中tryUpdatingSelectedWord()调用该方法,将其强制为纯文本,然后执行selectedTextCallback异步回调函数。
  • selectTextCallback执行作为方法的回调参数getSelectedDataAsync传递的异步回调函数时,它会在回调返回时获取所选文本的值。 它通过使用返回AsyncResult对象的 value 属性,从回调的 selectedText 参数 (获取该值,该参数的类型为 AsyncResult) 。
  • 函数中的 selectedTextCallback 其余代码在 XML Web 服务中查询定义。
  • .js 文件中的其余代码显示外接程序 HTML UI 中的定义列表。

在 Visual Studio 中外接程序的 Web 应用程序项目中,可以将 ./Home.js 文件的内容替换为以下示例 JavaScript。

// The document the dictionary add-in is interacting with.
let _doc;
// The last looked-up word, which is also the currently displayed word.
let lastLookup;

// The base URL for the OfficeDefinitions-conforming XML web service to query for definitions.
const xmlServiceUrl = "DictionaryWebService.asmx/Define";

// Initialize the add-in.
// Office.initialize or Office.onReady is required for all add-ins.
Office.initialize = function (reason) {
    // Checks for the DOM to load using the jQuery ready method.
    $(document).ready(function () {
        // After the DOM is loaded, app-specific code can run.
        // Store a reference to the current document.
        _doc = Office.context.document;
        // Check whether text is already selected.
        tryUpdatingSelectedWord();
        // Add a handler to refresh when the user changes selection.
        _doc.addHandlerAsync("documentSelectionChanged", tryUpdatingSelectedWord);
    });
}

// Executes when event is raised on the user's selection changes, and at initialization time.
// Gets the current selection and passes that to asynchronous callback function.
function tryUpdatingSelectedWord() {
    _doc.getSelectedDataAsync(Office.CoercionType.Text, selectedTextCallback);
}

// Async callback that executes when the add-in gets the user's selection. Determines whether anything should
// be done. If so, it makes requests that will be passed to various functions.
function selectedTextCallback(selectedText) {
    selectedText = $.trim(selectedText.value);
    // Be sure user has selected text. The SelectionChanged event is raised every time the user moves
    // the cursor, even if no selection.
    if (selectedText != "") {
        // Check whether the user selected the same word the pane is currently displaying to
        // avoid unnecessary web calls.
        if (selectedText != lastLookup) {
            // Update the lastLookup variable.
            lastLookup = selectedText;
            // Set the "headword" span to the word you looked up.
            $("#headword").text("Selected text: " + selectedText);
            // AJAX request to get definitions for the selected word; pass that to refreshDefinitions.
            $.ajax(xmlServiceUrl,
                {
                    data: { word: selectedText },
                    dataType: 'xml',
                    success: refreshDefinitions,
                    error: errorHandler
                });
    }
}

// This function is called when the add-in gets back the definitions target word.
// It removes the old definitions and replaces them with the definitions for the current word.
// It also sets the "See More" link.
function refreshDefinitions(data, textStatus, jqXHR) {
    $(".definition").remove();

    // Make a new list item for each returned definition that was returned, set the CSS class,
    // and append it to the definitions div.
    $(data).find("Definition").each(function () {
        $(document.createElement("li"))
            .text($(this).text())
            .addClass("definition")
            .appendTo($("#definitions"));
    });

    // Change the "See More" link to direct to the correct URL.
    $("#SeeMoreLink").attr("href", $(data).find("SeeMoreURL").text());
}

// Basic error handler that writes to a div with id='message'.
function errorHandler(jqXHR, textStatus, errorThrown) {
    document.getElementById('message').innerText
      += ("textStatus:- " + textStatus
          + "\nerrorThrown:- " + errorThrown
          + "\njqXHR:- " + JSON.stringify(jqXHR));
}

试用

  1. 使用 Visual Studio,通过按 F5 或选择“调试>开始调试”以启动 Word功能区上显示的“显示任务窗格加载项”按钮来测试新创建的 Word 加载项。 加载项本地托管在 IIS 上。

  2. 在 Word,如果加载项任务窗格尚未打开,请选择“开始”选项卡,然后选择“显示任务窗格”按钮以打开加载项任务窗格。 (如果你使用的是批量许可的 Office 永久版本,而不是 Microsoft 365 版本或零售永久版本,则不支持自定义按钮。相反,任务窗格将立即打开。)

    突出显示“显示任务窗格”按钮的Word应用程序。

  3. 在Word中,向文档添加文本,然后选择任何或所有文本。

    字典任务窗格 UI。