with JavaScript


Create Project Folder

Open Visual Studio and create a New Project.
Find "Word Web Add-in" (with C#) and press Next.
Change the Project Name to "WordVisualStudio".
Change the Location by clicking on the Browse button.
Tick the "Place solution and project in the same directory" checkbox and press Create.
Note: The "Create Office Add-in wizard" does not appear (which it does with Excel and PowerPoint).
This will create a solution that contains two projects:
WordVisualStudio - This contains the XML manifest file.
WordVisualStudioWeb - This contains the corresponding HTML pages.


WordVisualStudio.xml

<?xml version="1.0" encoding="UTF-8"?> <OfficeApp 
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">

  <Id> Unique GUID </Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Better Solutions Limited</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="WordVisualStudio" />
  <Description DefaultValue="WordVisualStudio"/>
  <IconUrl DefaultValue="~remoteAppUrl/Images/Button32x32.png" />
  <SupportUrl DefaultValue="http://bettersolutions.com" />
  <AppDomains>
    <AppDomain>AppDomain1</AppDomain>
  </AppDomains>
  <Hosts>
    <Host Name="Document" />
  </Hosts>
  <DefaultSettings>
    <SourceLocation DefaultValue="~remoteAppUrl/Home.html" />
  </DefaultSettings>
  <Permissions>ReadWriteDocument</Permissions>
  <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">
    <Hosts>
      <Host xsi:type="Document">
        <DesktopFormFactor>
          <GetStarted>
            <Title resid="Contoso.GetStarted.Title"/>
            <Description resid="Contoso.GetStarted.Description"/>
            <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
          </GetStarted>
          <FunctionFile resid="Contoso.DesktopFunctionFile.Url" />
          <ExtensionPoint xsi:type="PrimaryCommandSurface">
            <OfficeTab id="TabHome">
              <Group id="Contoso.Group1">
                <Label resid="Contoso.Group1Label" />
                <Icon>
                  <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                  <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                  <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                </Icon>
                <Control xsi:type="Button" id="Contoso.TaskpaneButton">
                  <Label resid="Contoso.TaskpaneButton.Label" />
                  <Supertip>
                    <Title resid="Contoso.TaskpaneButton.Label" />
                    <Description resid="Contoso.TaskpaneButton.Tooltip" />
                  </Supertip>
                  <Icon>
                    <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                    <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                    <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                  </Icon>
                  <Action xsi:type="ShowTaskpane">
                    <TaskpaneId>ButtonId1</TaskpaneId>
                    <SourceLocation resid="Contoso.Taskpane.Url" />
                  </Action>
                </Control>
              </Group>
            </OfficeTab>
          </ExtensionPoint>
        </DesktopFormFactor>
      </Host>
    </Hosts>
    <Resources>
      <bt:Images>
        <bt:Image id="Contoso.tpicon_16x16" DefaultValue="~remoteAppUrl/Images/Button16x16.png" />
        <bt:Image id="Contoso.tpicon_32x32" DefaultValue="~remoteAppUrl/Images/Button32x32.png" />
        <bt:Image id="Contoso.tpicon_80x80" DefaultValue="~remoteAppUrl/Images/Button80x80.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="Contoso.DesktopFunctionFile.Url" DefaultValue="~remoteAppUrl/Functions/FunctionFile.html" />
        <bt:Url id="Contoso.Taskpane.Url" DefaultValue="~remoteAppUrl/Home.html" />
        <bt:Url id="Contoso.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" />
      </bt:Urls>
      <bt:ShortStrings>
        <bt:String id="Contoso.TaskpaneButton.Label" DefaultValue="Show Taskpane" />
        <bt:String id="Contoso.Group1Label" DefaultValue="Commands Group" />
        <bt:String id="Contoso.GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
      </bt:ShortStrings>
      <bt:LongStrings>
        <bt:String id="Contoso.TaskpaneButton.Tooltip" DefaultValue="Click to Show a Taskpane" />
        <bt:String id="Contoso.GetStarted.Description" DefaultValue="Your sample add-in loaded succesfully" />
      </bt:LongStrings>
    </Resources>
  </VersionOverrides>
</OfficeApp>

Home.html

This html file must include a reference to office.js
This html file must call its corresponding javascript file (Home.js).

<!DOCTYPE html> 
<html>
<head>
   <meta charset="UTF-8"/>
   <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
   <title>Word Add-In with Commands Sample</title>

   <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
   <script src="Scripts/jquery-3.5.0.js" type="text/javascript"></script>
   <script src="Scripts/MessageBanner.js" type="text/javascript"></script>
   <script src="Home.js" type="text/javascript"></script>

   <link href="Home.css" type="text/css" rel="stylesheet"/>
   <link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/9.6.0/css/fabric.min.css" />
   <link href="../Contents/Button.css" type="text/css" rel="stylesheet"/>
   <link href="../Contents/MessageBanner.css" type="text/css" rel="stylesheet"/>
</head>
<body>
    <div id="content-main">
        <div class="padding">
            <br />
            <div class="ms-font-xxl ms-fontColor-neutralSecondary ms-fontWeight-semilight">Sample</div>
            <br /><br />
            <div class="ms-font-xl ms-fontColor-neutralTertiary">Getting Started</div>
            <p class="ms-font-m-plus ms-fontColor-neutralTertiary" id="template-description"></p>
            <div class="ms-font-m"><a target="_blank" class="ms-Link ms-Link--hero"
            href="https://go.microsoft.com/fwlink/?LinkId=276812">Find more samples online</a></div>
            <br /><br />
            <button class="ms-Button ms-Button--primary" id="highlight-button">
                <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--plus"></i></span>
                <span class="ms-Button-label" id="button-text"></span>
                <span class="ms-Button-description" id="button-desc"></span>
            </button>
        </div>
    </div>
    <div class="footer">
        <div class="ms-Grid ms-bgColor-themeSecondary">
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12 ms-u-md12 ms-u-lg12">
                   <div class="ms-font-xl ms-fontColor-white">Contoso</div></div>
            </div>
        </div>
    </div>

    <div class="ms-MessageBanner" id="notification-popup">
        <div class="ms-MessageBanner-content">
            <div class="ms-MessageBanner-text">
                <div class="ms-MessageBanner-clipper">
                    <div class="ms-font-m-plus ms-fontWeight-semibold" id="notification-header"></div>
                    <div class="ms-font-m ms-fontWeight-semilight" id="notification-body"></div>
                </div>
            </div>
            <button class="ms-MessageBanner-expand" style="display:none">
            <i class="ms-Icon ms-Icon--chevronsDown"></i> </button>
            <div class="ms-MessageBanner-action"&ge</div>
        </div>
        <button class="ms-MessageBanner-close"> <i class="ms-Icon ms-Icon--x"> </i> </button>
    </div>
</body>
</html>

Home.js

The JQuery messageBanner control is part of the Office UI Fabric JavaScript components.
This control is used to display any errors at the bottom of the task pane.

(function () { 
    "use strict";

    var messageBanner;

    Office.initialize = function (reason) {
        $(document).ready(function () {
            var element = document.querySelector('.MessageBanner');
            messageBanner = new components.MessageBanner(element);
            messageBanner.hideBanner();

            if (!Office.context.requirements.isSetSupported('WordApi', '1.1')) {
                $("#template-description").text("This sample displays the selected text.");
                $('#button-text').text("Display!");
                $('#button-desc').text("Display the selected text");
                $('#highlight-button').click(displaySelectedText);
                return;
            }

            $("#template-description").text("This sample highlights the longest word in the text you have selected in the document.");
            $('#button-text').text("Highlight!");
            $('#button-desc').text("Highlights the longest word.");
            loadSampleData();
            $('#highlight-button').click(hightlightLongestWord);
        });
    };

    function loadSampleData() {
        Word.run(function (context) {
            var body = context.document.body;
            body.clear();
            body.insertText(
                "This is a sample text inserted in the document",
                Word.InsertLocation.end);

            return context.sync();
        })
        .catch(errorHandler);
    }

    function hightlightLongestWord() {
        Word.run(function (context) {
            var range = context.document.getSelection();
            var searchResults;
            
            context.load(range, 'text');

            return context.sync()
                .then(function () {
                    var words = range.text.split(/\s+/);
                    var longestWord = words.reduce(function (word1, word2) { return word1.length > word2.length ? word1 : word2; });

                    searchResults = range.search(longestWord, { matchCase: true, matchWholeWord: true });

                    context.load(searchResults, 'font');
                })
                .then(context.sync)
                .then(function () {
                    searchResults.items[0].font.highlightColor = '#FFFF00';
                    searchResults.items[0].font.bold = true;
                })
                .then(context.sync);
        })
        .catch(errorHandler);
    }

    function displaySelectedText() {
        Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    showNotification('The selected text is:', '"' + result.value + '"');
                } else {
                    showNotification('Error:', result.error.message);
                }
            });
    }

    function errorHandler(error) {
        showNotification("Error:", error);
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    }

    function showNotification(header, content) {
        $("#notification-header").text(header);
        $("#notification-body").text(content);
        messageBanner.showBanner();
        messageBanner.toggleExpansion();
    }
})();

Build and Run

Select (Debug > Start Debugging).
This will launch Word with an additional button added to the Home tab.
A "Getting Started" message will be displayed.

Press the Got It button to dismiss the popup message.
Press the "Show Taskpane" button to display the task pane.
Highlight the whole sentence and press the "Highlight" button.
The longest word in the current selection will be shaded yellow.


© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext