Giter Club home page Giter Club logo

office-js's Introduction

NPM Deployment Status

Office JavaScript APIs

The JavaScript API for Office enables you to create web applications that interact with the object models in Office host applications. Your application will reference the office.js library, which is a script loader. The office.js library loads the object models applicable to the Office application running the add-in.


About the NPM package

The NPM package for Office.js is a copy of what gets published to the official "evergreen" Office.js CDN, at https://appsforoffice.microsoft.com/lib/1/hosted/office.js.

The Office.js CDN contains all currently available Office.js APIs at any moment in time.

Each Office.js NPM package contains only Office.js APIs available on the Office.js CDN when the NPM package version was created.

Target scenarios

The NPM package for Office.js is intended as a way to obtain an offline copy (non-CDN) of the Office.js files, which can then be statically serve from your own site instead of using the CDN.

This NPM package is provided for the following scenarios.

  1. Development of an add-in behind a firewall, when accessing the Office.js CDN isn't possible.
  2. Offline access to the Office.js APIs to facilitate offline debugging.

Important: Office Add-ins published to AppSource must use the CDN reference. Offline Office.js references are only appropriate for internal development and debugging scenarios.

Best practices

Best practices for using the Office.js NPM package include:

Support

The Office.js CDN is the official supported source for Office Add-ins.

For the NPM package sourced through this repository, only the latest version of the package is supported. No support and no patches will be provided for previous versions of the package. The frequency of the updates to this repository and related NPM package to match the CDN version is not guaranteed.

Outlook add-ins don't support hosting Office.js offline due to network access requirements for dependencies like the Microsoft Ajax library.


Install the NPM package

To install "office-js" locally via the NPM package, run the following command.

npm install @microsoft/office-js --save


Our policy requires that developers always reference the latest version of Office.js library. This is to ensure that essential product updates are served quickly to the Office Add-ins by always referencing the latest release of the library for a given version, such as Generally Available (GA) version. Given that the latest Office.js release is backward-compatible with prior releases, it's safe to update to the most recent release of the library when one is available. Hence, only the latest version of Office.js NPM package is made available for installation.

Use the NPM package

Installing the NPM package locally creates a set of static Office.js files in the node_modules\@microsoft\office-js\dist folder of the directory where you ran the npm install command. To use the NPM package, do the following:

  1. Either manually or as part of a build script (e.g., CopyWebpackPlugin if you're using Webpack) have the files served from a destination of your choosing (e.g., from the /assets/office-js/ directory of your web server).

  2. Reference that location in a <script> tag within the HTML file in your add-in project.

For example, if you add the contents of the dist folder to the assets/office-js directory of your project, then you'd add the following <script> tag to your HTML file:

<script src="/assets/office-js/office.js"></script>

IntelliSense definitions

TypeScript definitions for Office.js are available.

Use TypeScript definitions with the NPM package

If you're using the Office.js NPM package for the firewall scenario and want a d.ts file that precisely matches the JS contents, use the d.ts file that's located within the /dist/office.d.ts folder of the NPM package. Achieve this by using a triple-slash reference.

  • TIP: If you create a references.ts file at the root of the project, simply point the reference to office.d.ts there.

If you don't need the firewall scenario, don't use the Office.js NPM package. Obtain the TypeScript definitions by using @types/office-js and reference the Office.js CDN at https://appsforoffice.microsoft.com/lib/1/hosted/office.js.

Enable IntelliSense in Visual Studio

Visual Studio 2017+ can use these same TypeScript definitions, even for regular JavaScript. For JavaScript IntelliSense in earlier versions of Visual Studio, an office-vsdoc.js is available alongside the office.js file. As long as you have a Scripts/_references.js file in your VS project, and as long as you substitute the existing triple-slash reference (/// <reference path="https://.../office.js" />) with the new location (the -vsdoc part gets substituted automatically, so use it just as you would in a <script src=""> reference), you should have the corresponding JavaScript IntelliSense.

NPM Package Versions

Office.js versioning is described in detail in https://learn.microsoft.com/office/dev/add-ins/develop/referencing-the-javascript-api-for-office-library-from-its-cdn. Importantly, there's a difference between what's in the JS files versus what are the capabilities of a particular computer (i.e., older or slower-to-update versions of Office).

The NPM package and the repo branches assume the following structure.

GitHub branch name NPM tag name Description
release latest Identical to a previous release on https://appsforoffice.microsoft.com/lib/1/hosted/office.js

The latest released publicly-available APIs.
beta beta Identical to a previous release on https://appsforoffice.microsoft.com/lib/beta/hosted/office.js

Forthcoming APIs, not necessarily ready for public consumption that may change. Possibly available on Insider Fast (and maybe Insider Slow) builds.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

More info

For more information on Office Add-ins and the Office JavaScript APIs, see:

Join the Microsoft 365 Developer Program

Join the Microsoft 365 Developer Program to get resources and information to help you build solutions for the Microsoft 365 platform, including recommendations tailored to your areas of interest.

You might also qualify for a free developer subscription that's renewable for 90 days and comes configured with sample data; for details, see the FAQ.

office-js's People

Contributors

alexjerabek avatar cproscia avatar elizabethsamuel-msft avatar jayrathi avatar kbrandl avatar keyur32 avatar lindalu-msft avatar microsoft-github-policy-service[bot] avatar msftenhanceprovenance avatar o365devx avatar rick-kirkham avatar shaofengzhu avatar sumurthy avatar wandyezj avatar zhenhuangmsft avatar zhngx avatar zlatkovsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

office-js's Issues

[Word Online] TypeError: Cannot read property 'Element' of null (in WordEditor.js)

When I search the Word Online template below called 'Simple resume' I get an error:
https://onedrive.live.com/embed?cid=F26A6E4F9EA8E142&resid=F26A6E4F9EA8E142%211229&authkey=AN_ljhP-Ylax418&em=2&wdStartOn=1

My code:

return Word.run(function(context) {
		var options = Word.SearchOptions.newObject(context);
		options.matchWildCards = true;

		var searchResults = context.document.body.search('[[]*[]]', options);
		context.load(searchResults, 'text');

		return context.sync().then(function() {
			console.log(JSON.stringify(searchResults.items));
		});
	})
	.catch(function(error) {
		console.log('Error: ' + JSON.stringify(error));
		if (error instanceof OfficeExtension.Error) {
			console.log('Debug info: ' + JSON.stringify(error.debugInfo));
		}
	});
}

Error:
WordEditor.js:3303 Uncaught (in promise) TypeError: Cannot read property 'Element' of null
at wac_QWa.Jm (WordEditor.js:3303)
at wac_hM.wG (WordEditor.js:3339)
at wac_iLa.Jt (WordEditor.js:2316)
at wac_bLa.Jt (WordEditor.js:2303)
at wac_8Ka.vFd (WordEditor.js:2293)
at wac_Dd.Zh (MicrosoftAjax.js:5)
at wac_Dd.Fe (WordEditor.js:250)
at wac_8Ka.wFd (WordEditor.js:2292)
at wac_Dd.Zh (MicrosoftAjax.js:5)
at wac_Dd.Fe (WordEditor.js:250)

My hunch:
It could have something to do with the search-text : '[[]*[]]'

PowerPoint Online access to slide show window

Message from office-js bot:
We’re closing this issue because it has been inactive for a long time. We’re doing this to keep the issues list manageable and useful for everyone. If this issue is still relevant for you, please create a new issue.
Thank you for your understanding and continued feedback.

Office.context.document.getActiveViewAsync function always return 'edit' even when I run presentation slide show. Happens only in browser. (Desktop version works fine).

Presentation opens in new window for slide show:
(ex: https://powerpoint.officeapps.live.com/p/PowerPointFrame.aspx?PowerPointView=SlideShowView)

Is there way to connect and get context/events from that slide show window?

Thanks in advance.

There is an error “Mismatched anonymous define() module” when using Requirejs and Office.js

In my Word AdIn I load two javasript files:

  1. office.js
  2. mybundle.js, includes requirejs
    In mybundle.js I use requirejs to load modules from my bundle. In most cases the error is thrown when the add in loads.
    image

Expected Behavior

I expect office-js not to interfere with using requirejs, one of the most common module loaders available.

Current Behavior

When word-win32-16.0.1.js. loads, it inserts a script tag for aria-web-telemetry.js which is the culprit of the error. The anonymous define is called at line 1, column 134 in aria-web-telemetry.js. The last line in the file is //# sourceMappingURL=aria-webjs-sdk-1.1.1.min.js.map if it guides you to the specific version of the file.

Steps to Reproduce, or Live Example

Create a Word AddIn project from Visual Studio 2017
Create a bundle file of significat size ~1Mb which includes requirejs.
Add a script reference to office.js
Add a script reference to the bundle file
Error is thrown when add-in is started.
Same issue is described here OfficeDev/office-js-docs#1181 (comment)

Context

I try to use requirejs to load my modules. The add-in does not work at all due to this error. I have a temporary work-around. I wait until all scripts are loaded on the page, including aria-web-telemetry.js and then insert a script tag to my bundle. In that case requirejs loads fine and my add-in works as expected.

Work-around
<script> function load() { console.log("load event detected!"); var ausc = document.createElement('script'); ausc.src = '@Url.Content("~/Scripts/vendor-bundle-prewrap.js")'; ausc.type = 'text/javascript'; ausc.setAttribute("data-main","aurelia-bootstrapper"); document.getElementsByTagName('head')[0].appendChild(ausc); } window.onload = load; </script>

The easiest solution would for you to just name the module, instead of beeing anonymous. Read more about the error message here http://requirejs.org/docs/errors.html#mismatch

Your Environment

Platform PC
Host Word
Office version 2016
Operating System Windows 10
Browser Chrome
Office-js file url https://unpkg.com/@microsoft/[email protected]/dist/office.js

No stack trace info when error happens in Office JS API

(Creating this issue per customer post in Stack Overflow: https://stackoverflow.com/questions/46294347/no-stack-trace-info-when-error-happens-in-office-js-api)

We're getting lots of Office JS API errors in Application Insights, but they don't have a stack trace. All that we have - The browser's same-origin policy prevents us from getting the details of this exception. Consider using 'crossorigin' attribute.. Note, we have set the crossorigin attribute to "office.js" in Add-In HTML:

<script src="//appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript" crossorigin="anonymous"></script>

The issue is this: office.js injects additional scripts depending on environment and these scripts don't have crossorigin set. For example, https://appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.01.js or the one which is injected in Outlook for Mac. It's really painful not to have access to stack trace.

[Excel] getSelectedRange() error

getSelectedRange throws an error if my selection is a ChartObject, a Shape, a Picture, an ActiveX Object or an embeded Office Addins object to name a few. Maybe there are other types too, but I don't recall right now.
My setup is Excel 365 v1706 / Windows 10, tested on ScriptLab.

I'm not sure if this is really a bug because the method name is get selected range, so it should throw an error if the selection is not a Range object. But, if you want to mirror the Application.ActiveCell property from VBA, it shouldn't throw an error.

I had this error because I was wondering if it is possible to get the selected object type, as I do in VBA: TypeName(Selection), but (I think) there is no such property as Application.Selection.

document.body.clear() fails with exceptions on Word Online Script Lab

Script Lab fails to clear document body on Word Online --

Script Lab public gist link

https://gist.github.com/kenual/31548c30cfb12004177af89d44effbe0

The same script works fine inside Script Lab on Word 365 Win32 Version 1706

Expected Behavior

After base64 file is inserted, context.document.body.clear() should succeed on Word Online just like Word on Windows.

Current Behavior

Script Lab shows Office JS exceptions running on Word Online

context.document.body.clear() should work on Word Online like it does on Word.

Steps to Reproduce, or Live Example

  • Link to live example: ______

Open Script Lab on Word Online
Open Basic API call (Javascript) sample
Copy github public gist

https://gist.github.com/kenual/31548c30cfb12004177af89d44effbe0

and paste into Script Lab Script

Click Run button to execute the Word JS block

  • Additional details:



Context

Our Add-in's primary users are on Word Online. This bug is causing our Add-in not able to update the document with updated file content. The same API call and functionality works fine on Word.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: Office Online
  • Host [Excel, Word, PowerPoint, etc.]: Word
  • Office version number: Version 1706
  • Operating System: Windows
  • Browser (if using Office Online): Chrome

Useful logs

  • Console errors
  • Screenshots
  • Test file (if only happens on a particular file)

Table's worksheet/id doesn't load on certain Excel Desktop builds

We have built an Excel Task pane add in that primarily works with tables. In few versions of Excel we get an error when we try to load tables from workbook.

Expected Behavior

Table's worksheet/id should be loaded

Current Behavior

Sample code to load tables from workbook:
$scope.findTables = function () {
let tables;
Excel.run(function (ctx) {
let xlTables = ctx.workbook.tables;
xlTables.load(["count", "items"]);
return ctx.sync(xlTables).then(function (xlTables) {
tables = new Array(xlTables.count);

        let loader = OfficeExtension.Promise.resolve({});
        xlTables.items.forEach(function (xlTable, i) {

            loader = loader.then(function () {
                xlTable.load(["id", "name", "worksheet/id"]);
                let tblRange = xlTable.getRange();
                prepare(tblRange);
                return ctx.sync(tblRange);

            }).then(function (tblRange) {

                let keyCellRow = tblRange.rowIndex + rowOffset,
                    keyCellColumn = tblRange.columnIndex + colOffset;

                let keyRange = ctx.workbook.worksheets.getItem(xlTable.worksheet.id).getCell(keyCellRow, keyCellColumn); //error thrown at this line
                keyRange.load(["formulas", "values"]);

                return ctx.sync().then(function () {
                    return keyRange.formulas[0][0] ? keyRange.formulas[0][0] : keyRange.values[0][0];
                });

            }).then(function (keyValue) {

                if (!keyValue) return;

                let tableRef = {
                    id: xlTable.id,
                    sheet: xlTable.worksheet.id,
                    name: xlTable.name,
                    key: keyValue
                };
                tables[i] = tableRef;
            });
        });
        return loader;
    });
}).then(function () {
    console.log("No of Tables", tables.length);
    app.showNotification("No of Tables detected: " + tables.length);
}).catch(function (error) {
    app.showNotification("Error in detecting tables");
    console.log("Error: " + error);
    logError(JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

}

The error we get is property id of worksheet not loaded. Note that here in sample code xlTable.load(["id", "name", "worksheet/id"]) and context.sync both are called only after that worksheet.id is accessed. But it still throws the error.

Here is the detailed error:

{
"name": "OfficeExtension.Error",
"code": "PropertyNotLoaded",
"message": "The property 'id' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.",
"traceMessages": [],
"innerError": null,
"debugInfo": {
"code": "PropertyNotLoaded",
"message": "The property 'id' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.",
"errorLocation": "Worksheet.id"
},
"stack": "PropertyNotLoaded: The property 'id' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.\n at t.throwIfNotLoaded (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:261181)\n at id.get (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:286763)\n at Anonymous function (https://smart-client.ngrok.io/app/Home.js:44:29)\n at yi (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:246431)\n at st (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:246518)\n at d (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:246338)\n at c (https://appsforoffice.microsoft.com/lib/1/hosted/excel-win32-16.01.js:21:244924)"
}

Steps to Reproduce, or Live Example

Here is a sample add in demonstrating this issue: https://1drv.ms/f/s!AkR0pKvDAOt3hEOiXMGyl8a6Ov40

Your Environment

Note that this happens only on specific build versions of Excel. We have observed this issue on 16.0.4498.1000, 16.0.4549.1000, 16.0.4619.1000 build versions.

We have posted this issue on Stack Overflow as well (https://stackoverflow.com/questions/45719649/tables-worksheet-id-doesnt-load-on-certain-excel-desktop-builds) but couldn't get a response.

Any inputs as to what is causing this or possible workaround would be helpful.

Thanks

Closing Office dialog with ESC while Iframe element has focus leads to bug

Exactly as title says: when you hit escape while focusing on an element in the dialog Iframe (say, an input or select) then dialog closes. The dialog can not be opened again.

Expected Behavior

The dialog closes, ánd emits an event with error 12006 (dialog closed by user).

Current Behavior

The dialog closes, and does not emit anything. on top of that, reopening the same dialog shows no dialog.
screenshot 2018-12-05 at 15 16 37

Request: Please provide a method to get the selected Timezone's offset in calendar.

Summary: I want to get the selected timezone's offset from UTC of the calendar event.

image

Here I want to get the Pacific Time Zone's offset but I only get the offset of the timezone I am already in.
(IST)
Expectation: Office.context.mailbox.item should have a method that gives me the selected timezone or rather preferably the timezone's offset of the calendar event.

Current Behavior:
Office.context.mailbox.item._data$p$0._data$p$0.timeZoneOffsets is an array containing only the timezone offsets of the timezone the user is currently in (In which he/she is creating the event in calendar.)

Change from Current Behavior:
Is it possible to provide the selected time zone's offset in some or any other preferred way?

  1. Login into your outlook web application using valid account credentials.
  2. Assuming you see the mail's inbox directly (navigate to the mailbox if not) after logging in, Click the calendar icon at the bottom for creating a new Calendar event.

Unable to get the selected timezone's offset from the Outlook api.

Context:
Our Add-in has email contacts that are in different timezone than that of the selected timezone, So timezone offset is required to set the appointment time correctly in the Add-in's contact page (although it is already handled for the outlook contact in outlook email, but need the offset to adjust the time in the Add-in's contact page.)

Environment:
Platform: PC
Host: Outlook web.
office-js version: v1.1
Operating System: Windows 7
Browser (if using Office Online): No, Chrome v61

CDN Issue - Source Maps for ariatelemetery 404 Response

Looks like the CDN version is having an issue loading source maps for ariatelemetry. I'm guessing since this a Production endpoint that we wouldn't want to load sourcemaps. But, I wanted to bring it to your attention just encase you hadn't seen it yet.

screen shot 2017-11-01 at 12 08 40 pm

Regards,
Lance

Worksheet.WorksheetProtection.protect() method fails if any parameter is passed

If the method in the title is called with a parameter, it always throws : “InvalidArgument: The argument is invalid or missing or has an incorrect format”.

Expected Behavior

The method should protect/unprotect the sheet in accordance with the options passed in the WorksheetProtectionOptions object.

Current Behavior

If any WorksheetProtectionOptions object is passed to the method, it throws “InvalidArgument: The argument is invalid or missing or has an incorrect format”.

Steps to Reproduce, or Live Example

Context

I need to be able to selectively protect the worksheet from some user actions, but not all. This requires a WorksheetProtectionOptions parameter.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: PC Desktop
  • Host [Excel, Word, PowerPoint, etc.]: Excel
  • Office version number: 1712, 8801.1000 Click-to-run
  • Operating System: Win 10
  • Browser (if using Office Online):N/A

Info Icon on Mac Task Pane Apps

My issue is related to the info icon that appears whenever the task pane is active on OSX. It is in a really annoying place for the task pane app I'm working on, blocking the main menu option. Due to consistencies with other platforms moving this menu icon is not an option. Frustratingly this info box appears in different places on Windows, Mac, and iPad. Is there any plan to allow us to change the location of this icon in our add-in/manifest file? (if there already is a way could you point me to the documentation?)

Keyboard shortcut support

Expected Behavior

Support for key combo press (keyboard shortcut) event trigger.

Current Behavior

Currently, we can only trigger add-in reaction by

  • adding new UI component on Ribbon / side panel;
  • adding selection in the context menu (right-click triggered).

Context

Many user scenarios call for continuous and seamless environment change.

An existing example is the equation editor. In desktop client of Word, PowerPoint and OneNote, we can create new equation field by pressing Alt + =.

Case: code pieces in document

Take code formatting as an example. The solutions we have now are very limited. They all have unsatisfactory experiences.

Analysis: Pasting from other text editor

We can copy HTML-formatted code from VS Code or other code editors into Word. However, it involves launching instances of other applications.

Analysis: Existing Add-in code format

Or, we can use the existing code format add-in. If a user wants to write directly in Word document, he is then required to edit the code in regular text environment first, where auto-indentation and auto-capitalization experience can be horribly disturbing. It also requires the user to do selection after they get the code ready.

Ideal flow

  1. Create a new field by pressing combo key, like Alt + ,, or Alt + Shift + {,
  2. A new field is created and cursor is active inside it,
  3. A ribbon tab is highlighted, with options to publish the snippet as a Gist, or to the user defined endpoint,
  4. When the user get his cursor outside this region, the field becomes inactive, and code highlighter is executed on the given code snippet.

Wrapping up

From discussion with staffs here at O365 DevDays 2017 in Shanghai, there are no current public API available for such experiences. They suggest that an issue should be posted here to stress such needs. The proposed ideal flow case also requires other potential API creations. However, the general idea here is to further modularize document elements and integrate them more seamlessly, in a way that is similar to the Python Jupyter Notebook experience or Mathematica Notebook experience.

Is it possible to change selection after setSelectionDataAsync?

Insert any text with setSelectionDataAsync API method, text appears in a document in selected state.

Is it possible, using Office JS API (or maybe other approach), to remove selection from pasted text and place cursor at the end of the inserted text?

  • Platform : PC
  • Host : Word
  • Office version number: 2013
  • Operating System: Win 10

The Office.context.officeTheme property is undefined in Outlook 2016

The property Office.context.officeTheme is undefined when used in the Outlook application: Official documentation. In Word, Excel and PowerPoint, the property is defined and I can access its children properties (bodyBackgroundColor, controlForegroundColor, etc...). I tried with both latest (1.1.0.13) and previous (1.1.0.12) versions of Office.JS but it doesn't work.

Expected Behavior

The officeTheme property inside the context provides bodyBackgroundColor, controlForegroundColor, etc... in all applications

Current Behavior

The officeTheme property inside the context is undefined in Outlook

Steps to Reproduce, or Live Example

Office.initialize = function (reason) {
    $(document).ready(function () {

        // The "Office" object and its "context" property are valid but the "officeTheme" property is undefined.
        // This works in Word, Excel and PowerPoint but not in Outlook.
        if (!Office.context.officeTheme) {
            console.log("Office theme not loaded");
        }
    });
}

Your Environment

PC desktop
Outlook 2016
Version 1711 Build. 8730.2127

Text insertion in specific place disappear after focus back to the document

I use MS word add in, for example Script Lab, when I try to insert text in specific position(double click anywhere in document) and switch to document my insertion disappears.

Expected Behavior

Inserted text should remain on the same place and should not disappear

Steps to Reproduce, or Live Example

  • Open word
  • create new document
  • open Script lab add in
  • double click in any place in the document
  • insert simple text using Script Lab(for example 'basic document assemble -> add h1 title')
  • click on the document to focus it
  • click on the document one more time
  • inserted text disappear

Your Environment

Platform : PC
Host : Word 15, Word 16
Office version number: 2013, 2016
Operating System: Win 10

Example

https://1drv.ms/v/s!AjsNYhyPk0sRhU5MrvLIMmNHyLtL

getAsync for TO field in Compose mode returns empty array when manually entering email address

Expected Behavior

return email address

Current Behavior

returns empty array when manually entering email address and not clicking enter, the address appears greyed.
returns correct value when selecting existing contact

Steps to Reproduce, or Live Example

  1. create new email
  2. manually print new address in TO field. Don't select from existing contacts and don't click enter!
  3. execute:
Office.cast.item.toItemCompose(Office.context.mailbox.item).to.getAsync(res => {
            if(res.status === Office.AsyncResultStatus.Succeeded) {
                    console.log('value: ', res.value);
           }
});

Your Environment

  • Platform: Mac
  • Host: Outlook
  • Office version number: 365
  • Operating System: El Capitane
  • Browser (if using Office Online): Chrome + Desktop Client

Office.context.document.removeHandlerAsync unexpected behavior during development with live-reload

Hi,

Thanks for a great product! I have an issue to report:

I am currently developing an Excel Add-in. I created the add-in using the Facebook create-react-app package from NPM and built from there. One of the great things about that framework is that it uses the WebPack live reload feature, so whenever I make a change to my code, it is automatically recompiled and the add-in reloads itself automatically (without having to close and reopen the Excel document). This has worked very well, but I noticed that my DocumentSelectionChanged event was being called multiple times for each time the event was called. Each time the page was live-reloaded, the callback repeat count would increase by one.

I figured out that it was because I was using an anonymous lambda function as the callback, so the Office JS framework was seeing it as a new callback each time, which makes sense. However, in the documentation for Office.context.document.removeHandlerAsync, it says that if you don't specify a handler to remove, it will remove all handlers for that event. I tried this, shown in the code below. The idea is to remove any old handlers, then in the callback to that async call, add the fresh handler back.

        // Remove all old handlers by sending an empty options object
        Office.context.document.removeHandlerAsync(Office.EventType.DocumentSelectionChanged, { }, (result) => {
            if (result.status === Office.AsyncResultStatus.Succeeded) {
                // It always succeeds
               // Add the fresh callback back
                Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, (eventArgs) => { this.onExcelSelectionChanged(eventArgs) });
            }
            else {
                console.log("Failed to remove all old DocumentSelectionChanged handlers! " + result.error)
            }
        })

This did not seem to have any effect, and the multiple-callback chain remains. Is it because every time the add-in is live-reloaded, a new global Office object is created, and it can't see the callbacks added from the previous Office objects?

I thought it might have to do with the lambda functions, but I tried some vanilla global functions, and it behaved the same.

This is likely only a development issue, but it can be pretty annoying when the program slows to a crawl after a bunch of live-reloads.

Nick

5001, An internal error has occurred

Expected Behaviour

Update email address:
Office.cast.item.toItemCompose(Office.context.mailbox.item).to.setAsync(recipients, callback);

Current Behaviour

Receive an error: 5001, An internal error has occurred

Steps to Reproduce

It happens only when all these factors are combined together:

  1. Windows 10 (Outlook for Mac is OK)
  2. Outlook 365 desktop client (Outlook in browsers Chrome and IE11 are OK)
  3. Add-in is pinned (when it is not pinned - it is OK)
  4. Mail is forwarded or replied (new compose mail - is OK)

Your Environment

Platform: Outlook 365 desktop client
OS: Windows 10

Check if Office.js is loaded outside of Office client

I am making an application with angularjs which can be loaded in a browser as a web page or in Office as an add-in. So i load office.js in index.html for both cases. But I realise that we should not do <body ng-app="myApp"> and angular.bootstrap(document, ['myApp']) together, otherwise controllers will execute twice. So I decided to not write <body ng-app="myApp"> and always use angular.bootstrap in both cases (ie, web page & add-in).

So for a web page, I could write:

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
...

So for a web page, I need to write angular.bootstrap inside Office.initialize, and share other code with the case of add-in:

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    });
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
// share the same code

However, if I write these two cases together as follows, it works for a web page, whereas I gives Error: ng:btstrpd App Already Bootstrapped with this Element for add-in.

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
        console.log("bootstrapped inside Office.initialize")
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap']).

If I set a flag, console will display bootstrapped outside Office.initialize followed by isBootstrapped, then running the code will show that Office.context or Office.context.document is undefined:

var isBootstrapped = false;

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    isBootstrapped = true
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        if (isBootstrapped) console.log("isBootstrapped")
        else {
            angular.bootstrap(document, ['myApp'])
            console.log("bootstrapped inside Office.initialize")
        }
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])

So I really need an efficient way to check if Office.js is loaded outside of Office client (ie, whether it is a web page or an add-in), to decide which piece of angular.bootstrap should be executed.

GetFileAsync Excel Desktop

Currently, when you perform the following:

Office.context.document.getFileAsync(Office.FileType.Compressed, (result: Office.AsyncResult) => {
   // Get all slices
});

In Excel 2016 Desktop, inside the callback function result will have an error saying that this is denied due to permissions/access.

According to this Stack Overflow answer, this is currently not supported, which would give some meaning to the error message.

I think it is silly that this functionality works in Excel Online but not in the desktop version.

Is this a limitation of the current design of Excel Desktop? Or is this just not implemented in the Office JS API yet. If the later, is this functionality in the works?

Selection in drop down menu in Outlook is not working

Selection in drop down menu is not working. I have got reported from several customer about a problem in drop down menu on Office Outlook Add-ins. In our case it is iPlanner Pro. We ask some user to test on other ADD-INS and the problem was the same.

We found that it happens when using two screens. If I disconnect and are only using my laptop all works.

The problem relates to Outlook Office 365 Add-in where I cannot select any items from a drop down menu using the mouse. If I use the keyboard arrow I am able to select.

As we know Office Add-isn are using IE. I have been trying to see if there are any special settings in my IE. It is standard.

Notice! As I recall this was a problem before and it got solved, but now it is back again.

Please advice

Errors processing 10-12 page document in Office 365 @office-js

Word online almost always broken after manipulating with big documents.

Code example:
Word.run(function (context) {
let foundItems: Word.RangeCollection = context.document.body.search("and", { matchCase: false, matchWholeWord: false }).load('items/NoPropertiesNeeded');
return context.sync().then(function () {
for (var i = 0; i < foundItems.items.length; i++) {
foundItems.items[i].insertText('replaced', 'Replace');
}
});
}).catch(function (error) {
console.log(error);
});
It works, but when word online try to autosave changes,I get next error:

“POST https://word-edit.officeapps.live.com/we/OneNote.ashx 500 (Internal Server Error)” and then I need to reload page.

It works perfect in Desktop Word
Document20.docx

#office-js

Office.context.mailbox.item is null in ViewModel "ICalendarItemDetailsViewModelFactory"

Expected Behavior

When opening my add-in in an appointment that is displayed the the view model mentioned in the title, Office.context.mailbox.item should not be null.

Current Behavior

When opening my add-in in an appointment that is displayed the the view model mentioned in the title, Office.context.mailbox.item is always null. I don't mean Office.context.mailbox.item or Office.context.mailbox.item.itemId. Also this is working correctly for messages (e-mails).

Steps to Reproduce

  1. Create an add-in that works inline for calendar items (and mail items, if you wish).
  2. Have the add-in output Office.context.mailbox.item (e.g. via console.log()).
  3. Optional: Compare with the output if you open the add-in inside a message item (e-mail)

Context

Trying to use the add-in to link some data to the item whithin our CRM software. It works fine for e-mails (Office.MailboxEnums.ItemType.Message).
In edit mode the add-in is loaded inside the taskbar and the item is set.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: Office Online (OWA/Outlook on the web)
  • Host [Excel, Word, PowerPoint, etc.]: Outlook
  • Office version number: Exchange 2016 CU5 / API requirement set 1.5
  • Operating System: Windows 10
  • Browser (if using Office Online): Chromium

Useful logs

  • Console Error: "Uncaught TypeError: Cannot read property 'itemId' of null"
  • Inline add-in:
    image

Title of dialog does not change when user navigates to new page

Expected Behavior

When a user opens a dialog with our Dialog API, the dialog’s title is the of the form:
Add-in Name [- page title from <title> tag]
If there is no text in the page’s <title></title> tag, then only the Add-in Name appears.
When the dialog redirects or is navigated to a page that has a non-blank <title></title> tag, then the part of the dialog name to the right of the hyphen should change to match the new page's title.

Current Behavior

The part after the hyphen stays the same, so the name of the first page that was opened (if it had a non-blank <title></title> tag) remains there as long as the dialog is open.

Steps to Reproduce, or Live Example

Clone this repo: https://github.com/OfficeDev/Office-Add-in-Dialog-API-Simple-Example
Open it in Visual Studio.

Open Dialog.html and change it's title to <title>My first dialog</title>.
Add the following in the tag:

This page is titled My first dialog

Copy Dialog.html to OtherPage.html.
Open OtherPage.html and change it's title to <title>OtherPage</title>.
Add the following in the tag:
This page is titled OtherPage

Open Dialog.html again and change the single line of code in the one() method to:
window.location = "OtherPage.html";

Run the add-in with F5.
Press the Dialog from Taskpane button.
Press the Pick a number (popup) button. Notice that the dialog title ends with "My first dialog".
Press the "1" button on the dialog. Notice that you are routed to the OtherPage, but the dialog title does not change.

Context

This was reported by customer: OfficeDev/office-js-docs#1227

Your Environment

  • Platform PC desktop
  • Host Word
  • Office version number: 1712, 8822
  • Operating System: win

Search method has a limit of 256 characters.

Using the javascript api, I'm searching for a sentence in a Word document. If the sentence is over 256 characters, I get an invalid argument error.

Is there anyway to search a document with a string that's over 256 characters?

Thanks!

API 1.4: Document.open function

I 'm playing around with the new api version 1.4 (beta).
I'm wondering how I can use the new open function (https://github.com/OfficeDev/office-js-docs/blob/WordJs_1.4_OpenSpec/reference/word/document.md#open)?

I tried this but it doesn't work:

    function openDocument(fileBase64) {
        Word.run(function (context) {
            return context.sync().then(function () {
                var wordDocument = context.application.createDocument(fileBase64);
                if (wordDocument) {
                    //context.load(wordDocument, 'open');
                    wordDocument.open();
                }
            }).then(context.sync);
        }).catch(errorHandler);
    }

Actually the createDocument function returns a Document object! However I cannot open it :(
I get an error "Invalid Argument".

How is it intended to work?

Office Add-in JavaScript FileDownload not working with MAC

FileSaver library not work office add-ins with mac.

Expected Behavior
It should allow to us download file from word office add-ins on mac using filesaver javascript library , same as we can do with safari browser(version 10.1) with same code.

Current Behavior
We can't download file from word office add-ins on mac. it is getting error with open application dialog as in screen shot.
stackoverflowfiledownloadissue

Steps to Reproduce, or Live Example

  1. Create word office add-ins

  2. Create html button to invoke download file.

  3. Create API with return content data

  4. Call API in word office add-ins with XMLHttpRequest()

  5. Install FileSaver.JS using NPM command or insert manually.
    npm install file-saver --save
    bower install file-saver
    Additionally, typscript definitions can be installed via:
    npm install @types/file-saver --save-dev

  6. Construct your content in Blob Type same as following
    var blob = new Blob([oReq.response], { type: "application/octet-binary" });

  7. Use SaveAs method for FileSaver.js as following
    saveAs(blob, 'Test1234.docx');

`var getMessageUrl = "https://test.xxx.xxx/api/xxx/testcontroller/GetTest?id=121212121212";

		var oReq = new XMLHttpRequest();

		
		oReq.open("GET", getMessageUrl, true);
		oReq.responseType = "arraybuffer";
		oReq.setRequestHeader('X_ConnectTo', 'X-Author-CRM');
		oReq.setRequestHeader('Access-Control-Allow-Origin', '*');
		oReq.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
		oReq.setRequestHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type,Accept, Origin');
		oReq.setRequestHeader('Authorization', 'Bearer XXXXXXXXX-Token-XXXXXXX');
		oReq.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
		oReq.onload = function (oEvent) {
			var blob = new Blob([oReq.response], { type: "application/octet-binary" });	
			saveAs(blob, 'Test1234.docx');
		};

		oReq.send();`

Context
This is really important for us to deliverable this to our customer. we can't use document.createElement('a') for download file , as we already have this implementation in our current code but for security reason, we must removed this document.createElement('a'); from current code and use with filesaver javascript library approach but now , we are block with this issue.

Your Environment

OS - X EI Capitan (Version 10.11.6)
Office version :15.32
Safari version : 10.1.1

Useful logs
Refer my link for more details
https://stackoverflow.com/questions/44922159/office-add-in-javascript-filedownload-not-working-with-mac

Excel - Slow performance when hiding rows

Summary

I am trying to hide a lot of disjoint rows in an Excel spreadsheet and it takes a while to hide all of the rows. (It is totally possible there is a better way to hide all of these I am just not sure what that would be.)

Expected Behavior

I wouldn't have expected it to take so long or maybe I would expect a way to group a set of ranges into one action?

Current Behavior

I loop through a list of rows I need to hide and wait for it to finish. Maybe if there were a way to specify a set of ranges to hide all at once?

Steps to Reproduce, or Live Example

I created a gist with an example for an actual set of hidden rows my application attempted to hide.

The part in question is this bit of code here

return Excel.run(function (ctx) {

  var worksheet = ctx.workbook.worksheets.getActiveWorksheet();
  _.forEach(hiddenRows, function (rowData) {
    var range = worksheet.getRange(rowData.range);
    range.rowHidden = true;
  });

  return ctx.sync()
  .then(function () {
  }).catch(function (err) {
});

Context

My application is trying to pull some accounting data from a oracle database into a spreadsheet for our accounting team. We are trying to auto hide some of the data so they can immediately see the important parts right when the data loads. You can see by the sample data there are a lot of records being inserted into the spreadsheet so hiding some of the data is very important for us.

Also the data is ordered by groupings so combining these all into one hidden section probably isn't an option.

Environment

  • PC desktop, Mac, Office Online: We have accountants that use this application on a wide variety of devices
  • Excel
  • Excel 2016 1705
  • MacOS, Windows 10, Windows 7
  • IE 11, Chrome, Safari, Firefox, Edge

Useful logs

If you run the gist I provided as an Excel Office addin then it will tell you how long a set of hide operations took. On average it is about 2 minutes and 45 seconds.

importing metron.extender into TS or JSX file causes issues with Office.js API

Logging this issue to track a bug reported by a customer in this Stack Overflow post: https://stackoverflow.com/questions/45927586/office-js-typescript-metron-extender-error.

From the post:

If you import metron.extender into any TS or JXS file (even if you don't use it), none of the Office API (like Excel.run(ctx) will work). If you trap the error, you will get something like: Unable to set property 'isValid' of undefined or null reference.

(If/when I'm able to get more detailed repro steps from the customer, I'll add that info this issue.)

Need to use two clicks in document to make cursor active again after text insertion using add in

Expected Behavior

I expect to use one click to get cursor active

Current Behavior

Need to make two clicks to make cursor active

Steps to Reproduce, or Live Example

  • Open word
  • use blank document
  • With add in using shared api method setselectionDataAsync() insert text
  • click on the document to focus it
  • click on the document one more time to get active cursor

Your Environment

  • Platform : PC
  • Host : Word 15, Word 16
  • Office version number: 2013, 2016
  • Operating System: Win 10

Excel Online - Deleting sheets doesn't always work

It seems that deleting sheets does not always work in Excel online. It is strange because the function I have posted here works 100% of the time on the desktop Excel client and only works intermittently on Office online.

Expected Behavior

I expected the worksheet.delete() function to always work when supplying a valid sheet when trying to delete a sheet online.

Current Behavior

Calling worksheet.delete() works the first time you load the Excel online webpage (Not the task pane the entire page) then doesn't work again until you reload the entire Excel online page.

Steps to Reproduce, or Live Example

I have a sample delete function deployed on AWS so here is a link to the manifest file that way someone can run this function and verify the bug... or let me know I am doing something wrong ;)

  • Additional details:
    1. Create a few sheets so they can be deleted after clicking the run button. (Or don't, I am creating a new sheet and deleting all the old sheets so it should remove the default sheet then create a new sheet)
    2. Load this manifest for the desktop client and it works fine
    3. Load this manifest in Office online and it only works the first time the page loads?

Context

I am trying to build a report add-in for a client and we would like our run report button to remove all of the previous reports before creating the new report and they have accountants that use Excel online as their main driver.

Your Environment

  • Platform: Office Online, Mac, PC Desktop
  • Host: Excel
  • Office version number: Excel 2016 1705, and Excel Online
  • Operating System: Windows 10, Windows 7, MacOS
  • Browser (if using Office Online): Chrome, Edge, IE 11

Useful logs

The only error I am getting in Office online is a generic one.

{
   "name":"OfficeExtension.Error",
   "code":"GeneralException",
   "message":"An internal error has occurred.",
   "traceMessages":[],
   "innerError":null,
   "debugInfo":{
      "code":"GeneralException",
      "message":"An internal error has occurred."
   }
}

Office API 1.1 getTaskByIndexAsync gets lost if more than 10(ish) Project Tasks

Hello,
in the Code below, my Function buildTaskHierarchy below is never called where there are more than 10-11 Tasks in the Project; otherwise it works fine. This concerns Project 2016, which is needed for Office API 1.1.

I think it is clear that the Office API Async-Calls manager is being overloaded (this is almost visible in VisualStudio debugging) and gets lost after more than just 10 calls to getTaskByIndexAsync (multiplied by the number of Field values requested via getTaskFieldAsync -- in parallel -- in a loop).

Given that "in the current version of the JavaScript API for Office, the promises pattern only works with code for bindings in Excel spreadsheets and Word documents", it would appear that the Office API 1.1, despite providing the new Methods getTaskByIndexAsync and getTaskFieldAsync, does not actually permit the Developer to recover all necessary Task information (even if we are only talking about 3-4 Fields) for a real Project (i.e. one that has far more than 10 tasks), for which an Add-In might actually be of some value (if someone has a Project with 10 tasks, I don't imagine they need an Add-In).

I have just spent 3 days developing my Add-In -- which does not currently permit me to get all needed Project Task information en masse -- so can someone please tell me if this apparent issue with the API 1.1 is known, and will be fixed?

Cameron

...
maxTaskIndex = asyncResult.value;
for (var taskIndex = 1; taskIndex <= maxTaskIndex; taskIndex++) {
// For every Task (Index), get its GUID and then get needed Fields for Task
_projDoc.getTaskByIndexAsync(taskIndex, getTaskFieldsByGUID);
}
...
function getTaskFieldsByGUID(asyncResult) {
var taskGUID = asyncResult.value;
var taskJSON = {};

    taskJSON = { "taskGUID": taskGUID };
    tasksArray.push(taskJSON);

    // Get Task Name -- then store in Task JSON
    _projDoc.getTaskFieldAsync(taskGUID,
                                Office.ProjectTaskFields.Name,                      
                                { asyncContext: { "taskGUID": taskGUID,
                                                  "taskFieldID": Office.ProjectTaskFields.Name } },
                                pushTaskFieldIntoTaskJSON);
    // Get Task WBS (ID) -- then store in Task JSON
    _projDoc.getTaskFieldAsync(taskGUID,
                                Office.ProjectTaskFields.WBS,                       
                                { asyncContext: { "taskGUID": taskGUID,
                                                  "taskFieldID": Office.ProjectTaskFields.WBS } },
                                pushTaskFieldIntoTaskJSON);
    // Get Task Work -- then store in Task JSON
    _projDoc.getTaskFieldAsync(taskGUID,
                                Office.ProjectTaskFields.Work,
                                { asyncContext: { "taskGUID": taskGUID,
                                                  "taskFieldID": Office.ProjectTaskFields.Work } },
                                pushTaskFieldIntoTaskJSON);

...
function pushTaskFieldIntoTaskJSON(asyncResult) {

    // Capture the current Task Name and Value in the Task JSON on success
    for (taskArrayIndex = 0; taskArrayIndex < tasksArray.length; taskArrayIndex++) {

        // Start by finding current Task in global Task Array (by GUID)
        if (tasksArray[taskArrayIndex].taskGUID == asyncResult.asyncContext.taskGUID) {
            // Current Task JSON Object has been found in global Task Array
            switch (asyncResult.asyncContext.taskFieldID) {
                // Task Name
                case Office.ProjectTaskFields.Name:
                    tasksArray[taskArrayIndex].taskName = asyncResult.value.fieldValue;
                    break;
                // Task WBS (ID)
                case Office.ProjectTaskFields.WBS:
                    tasksArray[taskArrayIndex].taskWBS = asyncResult.value.fieldValue;
                    break;
                // Task Work (in hours)
                case Office.ProjectTaskFields.Work:
                    tasksArray[taskArrayIndex].taskWork = asyncResult.value.fieldValue;
                    break;
            }
            break;         // leave FOR immediately
        }
    }   // FOR

    if (taskArrayIndex == (maxTaskIndex - 1)) {          
        // Is this the last Task? Array Index starts at 0 unlike maxTaskIndex
        if (typeof tasksArray[taskArrayIndex].taskName !== 'undefined'
            && typeof tasksArray[taskArrayIndex].taskWBS !== 'undefined'
            && typeof tasksArray[taskArrayIndex].taskWork !== 'undefined') {

            // Once the last Task Field Value has been returned for the last Task ...
            buildTaskHierarchy();

...

Excel Online: tab key (for completion) doesn't work

Pressing "tab" in the IntelliSense completion list on Excel Online switches focus out of the editor and to... not sure where.

This makes it very hard to use the editor.

Coincidentally, the other shortcuts (ctrl+space, f1 for command palette, etc.) do work.

[* Only tested in Excel Online, but I assume the other Online clients will also experience the same problem]

GeneralException on context.sync after loading properties on Excel Online

Note:
I'm opening this issue on behalf of a customer, who originally opened the issue in the docs repo. Since this is potentially a product bug, this issue belongs here in the office-js repo. Here are the related issues that the customer logged in the docs repo:


Error on Javascript Console thrown after the first context.sync after loading properties on a writing text to cells in Excel Online. This does not appear to happen in Excel Applications for Windows and Mac, just Online.

r {name: "OfficeExtension.Error", code: "GeneralException", message: "Ocorreu um erro interno.", traceMessages: Array(0), innerError: null, …} code:"GeneralException" debugInfo:{code: "GeneralException", message: "Ocorreu um erro interno.", toString: ƒ} innerError:null message:"Ocorreu um erro interno." name:"OfficeExtension.Error" traceMessages:[] __proto__:Error

Code that is throwing this error:

$scope.writeText = function (item) { 
Excel.run(function (context) {                       
	var click = item.Click;
	var sourcestring = item.onAction;
	var excelString = item.excel;
	var sheet;
	var activeRange;
	var string;
	if (excelString === "") string = sourcestring;
	else string = excelString;
	sheet = context.workbook.worksheets.getActiveWorksheet();
	activeRange = context.workbook.getSelectedRange();
	activeRange.load('columnIndex');
	activeRange.load('rowIndex');
	return context.sync().then(function () {
	  CODE NOT EXECUTED, error thrown before this code
	}
   }
}

Expected Behavior

Expected behavior is for this code to run without error on all platforms (Excel 2016, Mac, Online).

Current Behavior

Code runs without error in Excel 2016 and on Mac, but the error noted above occurs in Online.

Context

This problem in Excel Online is permanent since November and has not been corrected. This is a serious issue, we can't launch a product because the add-in is not approved because it gets this error in Excel Online, and does not do what it is intended for.

Your Environment

  • Platform: Office Online
  • Host: Excel

Clicking an empty href “shrink” outlook web add in

Clicking an empty href “shrink” outlook web add in

Below is copy from Stack Overflow:


This is part question, part bug report. To reproduce I created a new project "Outlook Web Add In (C#)" in Visual Studio 2017.

Then it generates a default project. In the default project I change:

<p class="ms-font-xl ms-fontColor-themeDarkAlt ms-fontWeight-semilight">All properties</p>

to:

<a href="#"><p class="ms-font-xl ms-fontColor-themeDarkAlt ms-fontWeight-semilight">All properties</p></a>

Now it gets interesting, prior to clicking the newly created link everything looks as expected:

Prior to clicking

But then when I click the link all of the text in that HTML pane will shrink, more so with each subsequent click:

After clicking several times

No other modifications to the default project were made other than the <a href="#"> </a> around any given header tag. It will continue to shrink the more a user clicks.

Although it doesn't solve my question I have also worked around the bug by changing the href statement to the following:

 <a href="#" onclick="myfunction(); return false;">

My hypothesis is returning false is unexpected by whatever function is causing the content to reduce in size. Is this an expected behavior?

The "issue" of having to approve opening of a new window.

I'm using office js helpers( collection of helpers to simplify development of Office Add-ins) for a word addin that I am developing. When you open the addin in word online (office365), the authentication process starts and it opens up a small window (dialog) with the text (translated to english):

                 Templatehandler wants to open a new window  
                      

                                              Allow or Ignore   
                                             (Allow or ignore are buttons)

From the Company that I work for and from my own point of view, it would be nice to have the possibility to get rid of this windowprompt and allow the opening by default. It seems that this is more a platform-issue as Michael Zlatkovsky explained on Stackoverflow
He also suggested that I should do a bug report so it is getting tracked here =)

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: Office Online
  • Host [Excel, Word, PowerPoint, etc.]: Word
  • Office version number: ______1705
  • Operating System: ______Windows 10 Pro v 1709
  • Browser (if using Office Online): ______Chrome, Edge, Firefox

Useful logs

  • Console errors
  • Screenshots

newwindownotification

  • Test file (if only happens on a particular file)

Need worksheet codename that persists across sessions

Why don't we have a read-only worksheet codename that persists across sessions (like VBA)? The VBA codename is unique within a workbook and a workbook is unique within a session.
Without this JS code is vulnerable to the user changing worksheet name, and the ID property is only valid within a session so is not very useful.
In fact it would be even better to actually use the VBA Codename - it must be stored in the file structure somewhere - then it would make migrating VBA stuff to JS easier.

Remove script filename check

Expected Behavior

The "office.debug.js" should work as a part of a large file bundle.

Current Behavior

I concat all scripts in one bundle file "lib.js" for a traffic optimization.
Because of that the script file name validation fails:
Uncaught Office Web Extension script library file name should be office.js or office.debug.js.

Steps to Reproduce, or Live Example

Change the script file name.

Context

I concat all scripts in one bundle file "lib.js" for a network traffic optimization.
The solution is to remove the script filename check.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: Mac
  • Host [Excel, Word, PowerPoint, etc.]: Outlook
  • Office version number: 365

Excel - Slow performance when writing data into Table

Summary

I'm creating a table in Excel using the new Promise based API's and inserting data into it and the performance isn't what I would have expected.

const t0 = performance.now();
  
// add new table, set name and headers
 myTable = sheet.tables.add(tableRange, true);
 myTable.name = tableName;
 myTable.getHeaderRowRange().values = [headers];

// add data if exists
if (data.length > 0) {
 myTable.rows.add(null, data);
}
// activate sheet
sheet.activate();

await context.sync()
 .then(() => {
      const t1 = performance.now();
      console.log(`Took ${(t1 - t0).toFixed(4)} milliseconds to generate: ${tableName}`);
});

Expected Behavior

I would expect that 2000 records would be fast and only take 1 second or so and that I would be able to insert significantly more data. We are in the early phases of developing our add-in so we are using small datasets but in the future we want to support 100's of thousands of records. I recognize to insert that many records we will need to probably chunk it up and insert in batches but I would think those batches could be bigger than 2000 records???

Current Behavior

When I create a table and insert 100 records it is snappy and feels fast. Less than 1 second. However, when I load 2,000 records and 20 columns it is much slower. At worst I have seen 20 seconds and at best like 5 seconds.

  • Excel for Mac (Fast Insider 15.39): 13-20 seconds
  • Excel Online (Chrome 60): 5-8 seconds
  • Excel Online (Safari 10.1.2): 5-8 seconds
  • Excel 2016 for Windows (Version 1710 - Build 8530.1000) - 6-8 seconds

Steps to Reproduce, or Live Example

See code snippet above. It is basically the same as what is provided in ScripLab but the data is just 2000 records x 20 columns

Context

As mentioned above, I would expect 2000 records x 20 columns to be faster than it is because I want to be able to allow users to download large datasets (100,000 records+). Assuming, we can provide a good user experience.

Your Environment

  • Platform: Mac, Office Online
  • Host: Excel
  • Office version number: See above because I tested on multiple versions/browsers
  • Operating System: MacOS Sierra, Windows 10
  • Browser: Chrome 60 & Safari 10

Useful logs

I'm adding some Application Insight events right now and will update issue with some performance observations.

Questions:

  1. Is my code correct or is there a better way to be doing this?
  2. Are my expectations correct and inline with what I should be expecting?
  3. What is a good batch size for inserting data into a table? Records, columns or by number of cells?

Table.sort.reapply() crashes Excel

Expected Behavior

Table has been sorted. User changes one or more cell values in the sort-on column, so the table rows are no longer in the proper sort order. Code calls myTableObject.sort.reapply(). The table is resorted on the existing criteria so it is again in desired sort order.

Current Behavior

When myTableObject.sort.reapply() runs, Excel crashes. There is no error message.

Steps to Reproduce, or Live Example

  1. Create an add-in (or Script Lab snippet) that
    A. Calls myTableObject.sort.clear();
    B. Loads the TableSort object with myTableObject.load('sort');
    C. Calls context.sync
    D. Calls myTableObject.sort.reapply();
  2. Assign the function to a button.
  3. Create a table (manually or with code, doesn't matter) with 2 or more columns and rows. One column has text values that are NOT in alphabetical order.
  4. Sort the column in Z-A order.
  5. Change one of the column values so that it is out of order alphabetical order.
  6. Click the button.

Excel crashes.
The crash won't happen unless you call myTableObject.sort.clear(); before you call myTableObject.sort.reapply();. But Excel should not crash.

Context

I'm creating an Excel.js tutorial.

Your Environment

  • Platform [PC desktop, Mac, iOS, Office Online]: PC desktop
  • Host [Excel, Word, PowerPoint, etc.]: Excel
  • Office version number: 1712 8731,1000 Click to Run
  • Operating System: Win 10
  • Browser (if using Office Online): N/A

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.