### Example of starting web server with another SharePoint URL Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial-create-custom-functions An example of the command to start the web server and load the add-in in Excel on the web, using an alternative SharePoint document URL. ```command line npm run start -- web --document https://contoso-my.sharepoint-df.com/:t:/p/user/EQda453DNTpFnl1bFPhOVR0BwlrzetbXvnaRYii2lDr_oQ?e=RSccmNP ``` -------------------------------- ### Example of starting web server with SharePoint URL Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial-create-custom-functions An example of the command to start the web server and load the add-in in Excel on the web, using a SharePoint document URL. ```command line npm run start -- web --document https://contoso.sharepoint.com/:t:/g/EZGxP7ksiE5DuxvY638G798BpuhwluxCMfF1WZQj3VYhYQ?e=F4QM1R ``` -------------------------------- ### Example Installation Link for Script Lab Source: https://learn.microsoft.com/en-us/office/dev/add-ins/publish/publish-office-add-ins-to-appsource This is an example of a fully formed installation link for the Script Lab add-in in Word. ```URL ms-word:https://api.addins.store.office.com/addinstemplate/en-US/228a829b-69d7-45f4-a338-c6aba330ec7e/WA104380862/none/Script%20Lab,%20a%20Microsoft%20Garage%20project.docx?omexsrctype=1&isexternallink=1 ``` -------------------------------- ### Example of starting web server with OneDrive URL Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial-create-custom-functions An example of the command to start the web server and load the add-in in Excel on the web, using a OneDrive document URL. ```command line npm run start -- web --document https://1drv.ms/x/s!jkcH7spkM4EGgcZUgqthk4IK3NOypVw?e=Z6G1qp ``` -------------------------------- ### Example URLs for Sideloading in Browser Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react These are example URLs you can use with the 'npm run start -- web --document {url}' command to test your add-in with specific Excel documents hosted on SharePoint or OneDrive. ```bash npm run start -- web --document https://contoso.sharepoint.com/:t:/g/EZGxP7ksiE5DuxvY638G798BpuhwluxCMfF1WZQj3VYhYQ?e=F4QM1R ``` ```bash npm run start -- web --document https://1drv.ms/x/s!jkcH7spkM4EGgcZUgqthk4IK3NOypVw?e=Z6G1qp ``` ```bash npm run start -- web --document https://contoso-my.sharepoint-df.com/:t:/p/user/EQda453DNTpFnl1bFPhOVR0BwlrzetbXvnaRYii2lDr_oQ?e=RSccmNP ``` -------------------------------- ### Example URLs for Excel on the Web Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial These are example URLs that can be used with the 'npm run start -- web --document {url}' command to test your add-in in Excel on the web. ```command line npm run start -- web --document https://contoso.sharepoint.com/:t:/g/EZGxP7ksiE5DuxvY638G798BpuhwluxCMfF1WZQj3VYhYQ?e=F4QM1R ``` ```command line npm run start -- web --document https://1drv.ms/x/s!jkcH7spkM4EGgcZUgqthk4IK3NOypVw?e=Z6G1qp ``` ```command line npm run start -- web --document https://contoso-my.sharepoint-df.com/:t:/p/user/EQda453DNTpFnl1bFPhOVR0BwlrzetbXvnaRYii2lDr_oQ?e=RSccmNP ``` -------------------------------- ### Configure Get Started Message Requirements Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/requirements-property-unified-manifest The 'requirements' property within 'getStartedMessages' allows for conditional display of add-in descriptions. This example shows how to present different messages based on the ExcelApi version supported by the client. ```json "extensions": [ ... { ... "getStartedMessages": [ { "title": "Contoso Excel Formatting", "description": "Use conditional formatting with our add-in.", "learnMoreUrl": "https://contoso.com/simple-conditional-formatting-details.html", "requirements": { "capabilities": [ { "name": "ExcelApi", "minVersion": "1.6", "maxVersion": "1.16" } ] } }, { "title": "Contoso Advanced Excel Formatting", "description": "Use conditional formatting and dynamic formatting changes with our add-in.", "learnMoreUrl": "https://contoso.com/advanced-conditional-formatting-details.html", "requirements": { "capabilities": [ { "name": "ExcelApi", "minVersion": "1.17" } ] } } ] } ] ``` -------------------------------- ### Example Registry Keys for Add-in Installation Source: https://learn.microsoft.com/en-us/office/dev/add-ins/publish/publish-office-add-ins-to-appsource This example shows how to populate the registry keys for a specific add-in named 'ContosoAdd-in' with asset ID 'WA999999999' for the 'Word' application. ```plaintext // Only the current user. [HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Wef\AutoInstallAddins\Word\ContosoAdd-in] "AssetIds"="WA999999999" // All users of the computer. [HKEY_LOCAL_MACHINE\Software\Microsoft\Office\16.0\AutoInstallAddins\Word\ContosoAdd-in] "AssetIds"="WA999999999" ``` -------------------------------- ### Example Installation Link for Script Lab (Excel) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/publish/publish-office-add-ins-to-appsource This is an example of a fully formed installation link for the Script Lab add-in, specifically for opening in Excel on the web. The linkId '2261819' targets the Excel endpoint. ```URL https://go.microsoft.com/fwlink/?linkid=2261819&templateid=WA104380862&templatetitle=Script%20Lab,%20a%20Microsoft%20Garage%20project ``` -------------------------------- ### Start Local Web Server (Alternative for Desktop) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-custom-functions-quickstart Start the local web server and open your add-in in Excel on Windows or Mac. This command is used if your project does not have a 'start:desktop' script. ```command line npm run start ``` -------------------------------- ### Install Project Dependencies Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/outlook-tutorial Install the Showdown, URI.js, and jQuery libraries required for the add-in. ```command line npm install showdown urijs jquery --save ``` -------------------------------- ### Start the project Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/configure-your-add-in-to-use-a-shared-runtime Run this command to start the project after updating the taskpane.js file. ```command line npm start ``` -------------------------------- ### Install Office-Addin-Mock Source: https://learn.microsoft.com/en-us/office/dev/add-ins/testing/unit-testing Install the Office-Addin-Mock library as a development dependency for your add-in project. ```bash npm install office-addin-mock --save-dev ``` -------------------------------- ### Start Local Web Server Source: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/append-on-send Run this command in the project root to start the local web server and sideload your add-in. ```command line npm start ``` -------------------------------- ### Start Add-in on Desktop (Alternative) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-debugging Starts your add-in in the desktop version of Excel if the 'start:desktop' script is not present in your package.json. ```bash npm run start ``` -------------------------------- ### Start Local Web Server for Excel on Windows or Mac Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-custom-functions-quickstart Start the local web server and open your add-in in Excel on Windows or Mac. This command is used if your project has a 'start:desktop' script. ```command line npm run start:desktop ``` -------------------------------- ### Start Add-in on Desktop Source: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-debugging Starts your add-in in the desktop version of Excel. Use this if the 'start:desktop' script is available in your package.json. ```bash npm run start:desktop ``` -------------------------------- ### Update package.json start script Source: https://learn.microsoft.com/en-us/office/dev/add-ins/publish/deploy-office-add-in-sso-to-azure Replace the default start command in package.json with 'node middletier.js' to specify the entry point for the application. ```json "start": "node middletier.js" ``` -------------------------------- ### Install Office JavaScript Linter Source: https://learn.microsoft.com/en-us/office/dev/add-ins/overview/set-up-your-dev-environment Install the office-addin-lint and eslint-plugin-office-addins packages as development dependencies. ```command line npm install office-addin-lint --save-dev npm install eslint-plugin-office-addins --save-dev ``` -------------------------------- ### Specify Form Factors for Outlook Add-ins Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements-unified Use the 'requirements.formFactors' property to specify whether an Outlook add-in should be installable on desktop (including tablets) or mobile devices. This example makes the add-in installable only on desktop devices. ```json "extensions": [ { "requirements": { ... "formFactors": [ "desktop" ] }, ... } ] ``` -------------------------------- ### Example Flight Code URL for Restricted Listing Source: https://learn.microsoft.com/en-us/office/dev/add-ins/publish/autolaunch-store-options This is an example URL format used for restricted listings in Microsoft Marketplace, incorporating a flight code to control access. Users and admins must use this specific URL to install the add-in. ```url https://marketplace.microsoft.com/product/office/WA200002862?flightCodes=EventBasedTest1 ``` -------------------------------- ### Get the start time of an appointment (Compose Form) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/get-or-set-the-time-of-an-appointment This snippet demonstrates how to retrieve the start time of an appointment in a compose form using the `getAsync` method. It includes error handling and displays the time in both UTC and local formats. Ensure the Office.js library is loaded and the add-in is configured for Outlook compose forms. ```javascript let item; // Confirms that the Office.js library is loaded. Office.onReady((info) => { if (info.host === Office.HostType.Outlook) { item = Office.context.mailbox.item; getStartTime(); } }); // Gets the start time of the appointment being composed. function getStartTime() { item.start.getAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Failed) { write(asyncResult.error.message); return; } const startTime = asyncResult.value; // Display the start time in UTC format on the page. write(`The start time in UTC is: ${startTime.toUTCString()}`); // Display the start time in local time on the page. write(`The start time in local time is: ${startTime.toLocaleString()}`); }); } // Writes to a div with id="message" on the page. function write(message) { document.getElementById("message").innerText += message; } ``` -------------------------------- ### Initialize with Office.onReady() using a callback Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/initialize-add-in Use this method to perform initialization logic based on the host application and platform. The callback function receives an info object containing host and platform details. ```javascript Office.onReady(function(info) { if (info.host === Office.HostType.Excel) { // Do Excel-specific initialization (for example, make add-in task pane's // appearance compatible with Excel "green"). } if (info.platform === Office.PlatformType.PC) { // Make minor layout changes in the task pane. } console.log(`Office.js is now ready in ${info.host} on ${info.platform}`); }); ``` -------------------------------- ### Get Pages in Current Section Source: https://learn.microsoft.com/en-us/office/dev/add-ins/onenote/onenote-add-ins-programming-overview Retrieves and logs the ID and title of each page in the currently active OneNote section. This example demonstrates the load/sync pattern for interacting with OneNote objects. ```javascript async function getPagesInSection() { await OneNote.run(async (context) => { // Get the pages in the current section. const pages = context.application.getActiveSection().pages; // Queue a command to load the id and title for each page. pages.load('id,title'); // Run the queued commands, and return a promise to indicate task completion. await context.sync(); // Read the id and title of each page. $.each(pages.items, function(index, page) { let pageId = page.id; let pageTitle = page.title; console.log(pageTitle + ': ' + pageId); }); }); } ``` -------------------------------- ### Set up sample data and chart Source: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-charts-data-labels This code sample sets up the sample data and the 'Bicycle Part Production' chart used in the article. It creates a new worksheet, adds a table with sample data, and then creates a line chart based on that data. ```JavaScript async function setup() { await Excel.run(async (context) => { context.workbook.worksheets.getItemOrNullObject("Sample").delete(); const sheet = context.workbook.worksheets.add("Sample"); let salesTable = sheet.tables.add("A1:E1", true); salesTable.name = "SalesTable"; salesTable.getHeaderRowRange().values = [["Product", "Qtr1", "Qtr2", "Qtr3", "Qtr4"]]; salesTable.rows.add(null, [ ["Frames", 5000, 7000, 6544, 5377], ["Saddles", 400, 323, 276, 1451], ["Brake levers", 9000, 8766, 8456, 9812], ["Chains", 1550, 1088, 692, 2553], ["Mirrors", 225, 600, 923, 344], ["Spokes", 6005, 7634, 4589, 8765] ]); sheet.activate(); createChart(context); }); } async function createChart(context: Excel.RequestContext) { const worksheet = context.workbook.worksheets.getActiveWorksheet(); const chart = worksheet.charts.add( Excel.ChartType.lineMarkers, worksheet.getRange("A1:E7"), Excel.ChartSeriesBy.rows ); chart.axes.categoryAxis.setCategoryNames(worksheet.getRange("B1:E1")); chart.name = "PartChart"; // Place the chart below sample data. chart.top = 125; chart.left = 5; chart.height = 300; chart.width = 450; chart.title.text = "Bicycle Part Production"; chart.legend.position = "Bottom"; await context.sync(); } ``` -------------------------------- ### Start Debugging with Office Add-in Debugging CLI Source: https://learn.microsoft.com/en-us/office/dev/add-ins/testing/debug-desktop-using-edge-chromium Use this command in the root folder of your project to start debugging if you are not using a project created with Yo Office. Replace `` with the actual path to your add-in's manifest file. ```bash npx office-addin-debugging start ``` -------------------------------- ### Get Current Sensitivity Label of an Item Source: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/sensitivity-label Retrieve the GUID of the sensitivity label currently applied to an Outlook message or appointment. It's recommended to verify the catalog status first. ```javascript // It's recommended to check the status of the catalog of sensitivity labels before // calling other sensitivity label methods. Office.context.sensitivityLabelsCatalog.getIsEnabledAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Succeeded && asyncResult.value == true) { // Get the current sensitivity label of a message or appointment. Office.context.mailbox.item.sensitivityLabel.getAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Succeeded) { console.log(asyncResult.value); } else { console.log("Action failed with error: " + asyncResult.error.message); } }); } else { console.log("Action failed with error: " + asyncResult.error.message); } }); ``` -------------------------------- ### Declarative Agent Configuration Example Source: https://learn.microsoft.com/en-us/office/dev/add-ins/design/agent-and-add-in-overview Define the agent's name, description, conversation starters, and the API plug-in configuration file. This sets up the agent's behavior and capabilities. ```json { "$schema": "https://developer.microsoft.com/json-schemas/copilot/declarative-agent/v1.6/schema.json", "version": "v1.6", "name": "Excel Add-in + Agent", "description": "Agent for working with Excel cells.", "instructions": "You are an agent for working with an add-in. You can work with any cells, not just a well-formatted table.", "conversation_starters": [ { "title": "Change cell color", "text": "I want to change the color of cell B2 to orange" } ], "actions": [ { "id": "localExcelPlugin", "file": "Excel-API-local-plugin.json" } ] } ``` -------------------------------- ### Create a line Source: https://learn.microsoft.com/en-us/office/dev/add-ins/powerpoint/shapes This example demonstrates how to create a straight line on the first slide using the `addLine` method of the `ShapeCollection`. It specifies the connector type and the line's start and end points. ```APIDOC ## Create a line ### Description Creates a straight line on the first slide with specified start and end points. The line is assigned a name. ### Method ```javascript PowerPoint.run(async (context) => { // ... code to create line ... }); ``` ### Parameters - `PowerPoint.ConnectorType.straight`: Specifies the type of connector line. - `ShapeAddOptions` (optional): Specifies the start (`top`, `left`) and end (`height`, `width` relative to start) points of the line. ### Request Example ```javascript await PowerPoint.run(async (context) => { const shapes = context.presentation.slides.getItemAt(0).shapes; const line = shapes.addLine(PowerPoint.ConnectorType.straight, {left: 200, top: 50, height: 300, width: 150}); line.name = "StraightLine"; await context.sync(); }); ``` ### Response The `Shape` object representing the created line is returned and synchronized to the slide. ``` -------------------------------- ### Complete Startup Class with CORS Configuration Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/migrate-vsto-to-office-add-in-shared-code-library-tutorial This is an example of a complete `Startup` class in ASP.NET Core, including the CORS configuration for development. Ensure your localhost URL is correctly specified. ```csharp public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; public IConfiguration Configuration { get; } // NOTE: The following code configures CORS for the localhost:44397 port. // This is for development purposes. In production code, you should update this to // use the appropriate allowed domains. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://localhost:44397") .AllowAnyMethod() .AllowAnyHeader(); }); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors(MyAllowSpecificOrigins); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } ``` -------------------------------- ### Get Text Content Safely Source: https://learn.microsoft.com/en-us/office/dev/add-ins/concepts/privacy-and-security Use innerText or textContent to safely retrieve text from DOM elements, avoiding potential XSS vulnerabilities. This example provides cross-browser compatibility for Internet Explorer and Firefox. ```javascript var text = x.innerText || x.textContent ``` -------------------------------- ### Interact with Visio Page using run() Source: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/visio-api-reference This example demonstrates how to use the Visio.run() method to interact with the active Visio page. It shows how to get the active page and perform operations, ensuring proper error handling. ```TypeScript // *.run methods automatically create an OfficeExtension.ClientRequestContext // object to work with the Office file. Visio.run(session, function (context) { const activePage = context.document.getActivePage(); // Interact with the Visio page... return context.sync(); }).catch(function(error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); ``` -------------------------------- ### Initialize Office Add-in and Set Up Basic Structure Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial Sets up the initial Office.onReady function to ensure the add-in is loaded correctly in Excel. It hides a loading message and displays the main application body. ```typescript /* * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /* global console, document, Excel, Office */ Office.onReady((info) => { if (info.host === Office.HostType.Excel) { document.getElementById("sideload-msg").style.display = "none"; document.getElementById("app-body").style.display = "flex"; } }); ``` -------------------------------- ### Completed Registry Script for Trusted Network Share Source: https://learn.microsoft.com/en-us/office/dev/add-ins/testing/create-a-network-shared-folder-catalog-for-task-pane-and-content-add-ins This is an example of a completed .reg file after replacing the placeholder GUID and network path. This script registers a specific network share as a trusted catalog for Office Add-ins. ```text Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\WEF\TrustedCatalogs\{01234567-89ab-cedf-0123-456789abcedf}] "Id"="{01234567-89ab-cedf-0123-456789abcedf}" "Url"="\\TestServer\OfficeAddinManifests" "Flags"=dword:00000001 ``` -------------------------------- ### Start Local Web Server (Mac) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial Run this command in the root directory of your project to start the local web server when testing on a Mac. ```bash npm run dev-server ``` -------------------------------- ### Use Partition Key with Local Storage Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/persisting-add-in-state-and-settings This example demonstrates how to use Office.context.partitionKey to store and retrieve data from local storage, ensuring data is only accessible within the same context. It checks for the existence of the partition key before setting or getting items. ```javascript // Store the value "Hello" in local storage with the key "myKey1". setInLocalStorage("myKey1", "Hello"); // ... // Retrieve the value stored in local storage under the key "myKey1". const message = getFromLocalStorage("myKey1"); console.log(message); // ... function setInLocalStorage(key: string, value: string) { const myPartitionKey = Office.context.partitionKey; // Check if local storage is partitioned. // If so, use the partition to ensure the data is only accessible by your add-in. if (myPartitionKey) { localStorage.setItem(myPartitionKey + key, value); } else { localStorage.setItem(key, value); } } function getFromLocalStorage(key: string) { const myPartitionKey = Office.context.partitionKey; // Check if local storage is partitioned. if (myPartitionKey) { return localStorage.getItem(myPartitionKey + key); } else { return localStorage.getItem(key); } } ``` -------------------------------- ### Search Document Using Wildcards Source: https://learn.microsoft.com/en-us/office/dev/add-ins/word/search-option-guidance Searches the document using wildcard characters for flexible pattern matching. This example finds strings starting with 'to' and ending with 'n'. The found items have their font color, highlight color, and boldness modified. ```javascript // Run a batch operation against the Word object model. await Word.run(async (context) => { // Queue a command to search the document with a wildcard // for any string of characters that starts with 'to' and ends with 'n'. const searchResults = context.document.body.search('to*n', {matchWildcards: true}); // Queue a command to load the font property values. searchResults.load('font'); // Synchronize the document state. await context.sync(); console.log('Found count: ' + searchResults.items.length); // Queue a set of commands to change the font for each found item. for (let i = 0; i < searchResults.items.length; i++) { searchResults.items[i].font.color = 'purple'; searchResults.items[i].font.highlightColor = 'pink'; searchResults.items[i].font.bold = true; } // Synchronize the document state. await context.sync(); }); ``` -------------------------------- ### Start Sideloading with Office-Addin-Debugging Source: https://learn.microsoft.com/en-us/office/dev/add-ins/testing/sideload-add-in-with-unified-manifest Use this command to sideload an add-in with a unified manifest using the Office-Addin-Debugging tool. This command also starts a server to host the add-in files. ```bash npx office-addin-debugging start desktop ``` -------------------------------- ### Start Local Web Server for Excel on the Web Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-custom-functions-quickstart Start the local web server and open your add-in in Excel on the web. Replace '{url}' with the URL of your Excel document. ```command line npm run start -- web --document {url} ``` -------------------------------- ### Display a dialog to get a token Source: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-authentication Demonstrates using `OfficeRuntime.displayWebDialog` to open a dialog box for acquiring a token. This example shows the method's capabilities and is not a complete authentication solution. It includes logic to handle cases where a dialog is already open and to manage timeouts. ```javascript /** * Function retrieves a cached token or opens a dialog box if there is no saved token. Note that this isn't a sufficient example of authentication but is intended to show the capabilities of the displayWebDialog method. * @param {string} url URL for a stored token. */ function getTokenViaDialog(url) { return new Promise (function (resolve, reject) { if (_dialogOpen) { // Can only have one dialog box open at once. Wait for previous dialog box's token. let timeout = 5; let count = 0; const intervalId = setInterval(function () { count++; if(_cachedToken) { resolve(_cachedToken); clearInterval(intervalId); } if(count >= timeout) { reject("Timeout while waiting for token"); clearInterval(intervalId); } }, 1000); } else { _dialogOpen = true; OfficeRuntime.displayWebDialog(url, { height: '50%', width: '50%', onMessage: function (message, dialog) { _cachedToken = message; resolve(message); dialog.close(); return; }, onRuntimeError: function(error, dialog) { reject(error); }, }).catch(function (e) { reject(e); }); } }); } ``` -------------------------------- ### Initialize Office.js in Plain JavaScript Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/connect-to-javascript-frameworks Set up event handlers and check the host environment after Office.js is ready. This is suitable for projects without a specific framework. ```JavaScript // src/app.js Office.onReady((info) => { document.getElementById('run-button').onclick = run; if (info.host === Office.HostType.Excel) { console.log('Running in Excel'); } }); ``` -------------------------------- ### Get the subject of a composed item in Outlook Source: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/get-or-set-the-subject This example demonstrates how to retrieve the subject of an Outlook item that the user is currently composing. It includes error handling for the asynchronous call and displays the retrieved subject on the page. Ensure the Office.js library is loaded and the host is Outlook before calling `getSubject`. ```javascript let item; // Confirms that the Office.js library is loaded. Office.onReady((info) => { if (info.host === Office.HostType.Outlook) { item = Office.context.mailbox.item; getSubject(); } }); // Gets the subject of the item that the user is composing. function getSubject() { item.subject.getAsync((asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Failed) { write(asyncResult.error.message); return; } // Display the subject on the page. write(`The subject is: ${asyncResult.value}`); }); } // Writes to a div with id="message" on the page. function write(message) { document.getElementById("message").innerText += message; } ``` -------------------------------- ### Specify Requirement Sets and Methods in Manifest Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements Use the `Requirements` element in your Office Add-in manifest to declare the minimum API requirement sets and individual methods that must be supported by the Office application for your add-in to be installable. This example specifies support for `TableBindings` and `OoxmlCoercion` requirement sets, along with the `Document.getSelectedDataAsync` method. ```XML \n ...\n \n \n \n \n \n \n \n \n \n ...\n ``` -------------------------------- ### Install npm-check-updates Globally Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-jquery Install the npm-check-updates tool globally to help resolve dependency warnings. This command installs the tool. ```bash npm i -g npm-check-updates ``` -------------------------------- ### Build Add-in Files for Production Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/develop-add-ins-vscode Run this command in the root directory of your add-in project to prepare all files for production deployment. The build process creates a 'dist' folder containing deployable files. ```bash npm run build ``` -------------------------------- ### Start Add-in on the Web Source: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-debugging Starts your add-in in Excel on the web. Replace {url} with the URL of an Excel file on OneDrive or SharePoint. On Mac, enclose the URL in single quotes. ```bash npm run start -- web --document {url} ``` -------------------------------- ### Configure package.json for Desktop Debugging Source: https://learn.microsoft.com/en-us/office/dev/add-ins/testing/debug-desktop-using-edge-chromium Add these scripts to the `scripts` section of your `package.json` file to enable desktop debugging. The `start:desktop` script uses the `office-addin-debugging` package to start the add-in for debugging, and `dev-server` is used to launch your web server. ```json "start:desktop": "office-addin-debugging start $MANIFEST_FILE$ desktop", "dev-server": "$SERVER_START$" ``` -------------------------------- ### Skip Dependency Installation with Yeoman Generator Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/yeoman-generator-overview Add the `--skip-install` option to the 'yo office' command if you want to create the project scaffolding without immediately installing dependencies. You can install them later by running 'npm install' in the project's root folder. ```command line yo office --skip-install ``` -------------------------------- ### Install npm manually Source: https://learn.microsoft.com/en-us/office/dev/add-ins/overview/set-up-your-dev-environment Install npm globally if it's not already installed or if you need to update it manually. This command ensures you have the latest version of the npm package manager. ```command line npm install npm -g ``` -------------------------------- ### Recommended Project Structure (Simple) Source: https://learn.microsoft.com/en-us/office/dev/add-ins/overview/app-package-for-microsoft-365 This structure shows a basic recommended organization for your project files, including assets and the manifest, with the app package zip file located in a build subfolder. ```console \appPackage \assets color.png outline.png \build appPackage.zip manifest.json ``` -------------------------------- ### PowerPoint 'Hello World' Add-in Source: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/powerpoint-quickstart-yo A basic example of a PowerPoint add-in, consisting of a manifest, HTML web page, and a logo. ```html ``` -------------------------------- ### Initialize Office Add-in and Send File Source: https://learn.microsoft.com/en-us/office/dev/add-ins/develop/get-the-whole-document-from-an-add-in-for-powerpoint-or-word This is the main entry point for the Office Add-in. It initializes the Office object, sets up a click handler for a submit button to trigger the file sending process, and provides a function to update the status UI. ```javascript /* * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ // The initialize or onReady function is required for all add-ins. Office.initialize = function (reason) { // Checks for the DOM to load using the jQuery ready method. $(document).ready(function () { // Run sendFile when Submit is clicked. $('#submit').on("click", function () { sendFile(); }); // Update status. updateStatus("Ready to send file."); }) } // Create a function for writing to the status div. function updateStatus(message) { var statusInfo = $('#status'); statusInfo[0].innerHTML += message + "
"; } // Get all of the content from a PowerPoint or Word document in 100-KB chunks of text. function sendFile() { Office.context.document.getFileAsync("compressed", { sliceSize: 100000 }, function (result) { if (result.status === Office.AsyncResultStatus.Succeeded) { // Get the File object from the result. var myFile = result.value; var state = { file: myFile, counter: 0, sliceCount: myFile.sliceCount }; updateStatus("Getting file of " + myFile.size + " bytes") getSlice(state); } else { updateStatus(result.status); } }); } ``` -------------------------------- ### Show Office Add-in Project Structure Source: https://learn.microsoft.com/en-us/office/dev/add-ins/resources/resources-github-copilot-prompt-library Use this prompt to understand the typical structure of an Office Add-in project and the functionality of each file, including steps and commands for Visual Studio Code. ```prompt Show me the typical structure of an Office Add-in project and explain the functionality of each file. Explain the steps and commands to get started in *Visual Studio Code*. ```