Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@microsoft/applicationinsights-core-js

microsoft3.4mMIT3.3.8TypeScript support: included

Microsoft Application Insights Core Javascript SDK

azure, cloud, script errors, microsoft, application insights, browser performance monitoring, web analytics

readme

Application Insights JavaScript SDK

<properties pageTitle="Application Insights SDK JavaScript API" description="Reference doc" services="application-insights" documentationCenter=".net" />

<tags ms.service="application-insights" ms.workload="tbd" ms.tgt_pltfrm="ibiza" ms.devlang="na" ms.topic="article" ms.date="08/24/2015"/>

GitHub Workflow Status (master) npm version Build Status minified size size gzip size

Before Getting Started

This SDK is not for non-browser environments, for example, the Node.js applications.

For instrumenting a Node.js app, the recommended SDK is the ApplicationInsights-node.js repository.

ES3 support has been removed from the latest version (v3.x), if required see for ES3/IE8 Support

Release Versions

Version Details
3.x
(main)
Current supported release from April '2023.
Supports dynamic configuration changes/updates after initialization. Supports all features of v2 except with the known Breaking changes from previous versions and does NOT support the previous v1.x compatible API proxy layer, it also removes support for ES3 / IE8. Minimum supported Runtime is now ES5 (IE9+).
2.x
(master)
Feature freeze from March '2023, security fixes and critical bugs only.
Supports adding / removing extensions and full unloading/removal of the SDK after initialization. Last version to support ES3 (IE8+), also provides a v1.x compatible API proxy layer for upgrading from V1.x.
1.0.x
(legacy-v1)
No longer actively maintained -- please Upgrade. The documentation for `applicationinsights-js@1.0.x` has moved here. If you are looking to upgrade to the new version of the SDK, please see the Upgrade Guide.

Getting Started

  1. Create an Application Insights resource in Azure by following these instructions.
  2. Grab the Connection String from the resource you created in step 1. Later, you'll add it to the connectionString setting of the Application Insights JavaScript SDK.
  3. Add Application Insights to your app. There are 2 ways to do this.

Basic Usage

NPM Setup (ignore if using Snippet Setup)

import { ApplicationInsights } from '@microsoft/applicationinsights-web'

const appInsights = new ApplicationInsights({ config: {
  connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE'
  /* ...Other Configuration Options... */
} });
appInsights.loadAppInsights();
appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview

Snippet Setup (Ignore if using NPM Setup)

If your app does not use NPM, you can directly instrument your webpages with Application Insights by pasting this snippet at the top of each your pages. Preferably, it should be the first script in your <head> section so that it can monitor any potential issues with all of your dependencies.

The current version of the snippet is version 6, the version is identified by the "sv:" in the script.

<script type="text/javascript">
!function(v,y,T){var S=v.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w=(D[b](),"crossOrigin"),N="POST",e="appInsightsSDK",t=T.name||"appInsights",n=((T.name||v[e])&&(v[e]=t),v[t]||function(l){var u=!1,d=!1,g={initialize:!0,queue:[],sv:"6",version:2,config:l};function m(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(g.sv||g.version),{time:(a=new Date).getUTCFullYear()+"-"+i(1+a.getUTCMonth())+"-"+i(a.getUTCDate())+"T"+i(a.getUTCHours())+":"+i(a.getUTCMinutes())+":"+i(a.getUTCSeconds())+"."+(a.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}};function i(e){e=""+e;return 1===e.length?"0"+e:e}}var e,n,f=l.url||T.src;function a(e){var t,n,a,i,o,s,r,c,p;u=!0,g.queue=[],d||(d=!0,i=f,r=(c=function(){var e,t={},n=l.connectionString;if(n)for(var a=n.split(";"),i=0;i<a.length;i++){var o=a[i].split("=");2===o.length&&(t[o[0][b]()]=o[1])}return t[C]||(t[C]="https://"+((e=(n=t.endpointsuffix)?t.location:null)?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||l[D]||"",c=(c=c[C])?c+"/v2/track":l.endpointUrl,(p=[]).push((t="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",n=i,o=c,(s=(a=m(r,"Exception")).data).baseType="ExceptionData",s.baseData.exceptions=[{typeName:"SDKLoadFailed",message:t.replace(/\./g,"-"),hasFullStack:!1,stack:t+"\nSnippet failed to load ["+n+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+o,parsedStack:[]}],a)),p.push((s=i,t=c,(o=(n=m(r,"Message")).data).baseType="MessageData",(a=o.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+s+")").replace(/\"/g,"")+'"',a.properties={endpoint:t},n)),i=p,r=c,JSON&&((o=v.fetch)&&!T.useXhr?o(r,{method:N,body:JSON.stringify(i),mode:"cors"}):XMLHttpRequest&&((s=new XMLHttpRequest).open(N,r),s.setRequestHeader("Content-type","application/json"),s.send(JSON.stringify(i)))))}function i(e,t){d||setTimeout(function(){!t&&g.core||a()},500)}f&&((n=y.createElement(k)).src=f,!(o=T[w])&&""!==o||"undefined"==n[w]||(n[w]=o),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},e=n,T.ld<0?y.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){y.getElementsByTagName(k)[0].parentNode.appendChild(e)},T.ld||0));try{g.cookie=y.cookie}catch(h){}function t(e){for(;e.length;)!function(t){g[t]=function(){var e=arguments;u||g.queue.push(function(){g[t].apply(g,e)})}}(e.pop())}var s,r,o="track",c="TrackPage",p="TrackEvent",o=(t([o+"Event",o+"PageView",o+"Exception",o+"Trace",o+"DependencyData",o+"Metric",o+"PageViewPerformance","start"+c,"stop"+c,"start"+p,"stop"+p,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),g.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(l.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==l[I]&&!0!==o[I]&&(t(["_"+(s="onerror")]),r=v[s],v[s]=function(e,t,n,a,i){var o=r&&r(e,t,n,a,i);return!0!==o&&g["_"+s]({message:e,url:t,lineNumber:n,columnNumber:a,error:i,evt:v.event}),o},l.autoExceptionInstrumented=!0),g}(T.cfg));function a(){T.onInit&&T.onInit(n)}(v[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
    connectionString: "YOUR_CONNECTION_STRING"
}});
</script>

:bulb: Note

For readability and to reduce possible JavaScript errors, all of the possible configuration options are listed on a new line in snippet code above, if you don't want to change the value of a commented line it can be removed.

Reporting Script load exceptions

This version of the snippet detects and reports an exception when loading the SDK from the CDN fails, this exception is reported to the Azure Monitor portal (under the failures > exceptions > browser), and provides visibility into failures of this type so that you are aware your application is not reporting telemetry (or other exceptions) as expected. This signal is an important measurement in understanding that you have lost telemetry because the SDK did not load or initialize, this provides clarity that you are missing the following telemetry:

  • Under-reporting of how users are using (or trying to use) your site;
  • Missing telemetry on how your end users are using your site;
  • Missing JavaScript errors that could potentially be blocking your end users from successfully using your site.

For details on this exception see SDK Load Failure page.

Reporting of this failure as an exception to the portal does not use the configuration option disableExceptionTracking from the application insights configuration and therefore if this failure occurs it will always be reported by the snippet, even when the window.onerror support is disabled.

Reporting of SDK load exceptions is specifically NOT supported on IE 8 (or less). This assists with reducing the minified size of the snippet by assuming that most environments are not exclusively IE 8 or less. If you have this requirement and you wish to receive these exceptions, you will need to either include a fetch poly fill or create you own snippet version that uses XDomainRequest instead of XMLHttpRequest, it is recommended that you use the provided snippet source code as a starting point.

:bulb: Note

If you are using a previous version of the snippet, it is highly recommended that you update to the latest version so that you will receive these previously unreported issues.

Snippet configuration options

All configuration options have now been move towards the end of the script to help avoid accidentally introducing JavaScript errors that would not just cause the SDK to fail to load, but also it would disable the reporting of the failure.

Each configuration option is shown above on a new line, if you don't wish to override the default value of an item listed as [optional] you can remove that line to minimize the resulting size of your returned page.

The available configuration options are: -

Name Type Description
src string [required] The full URL for where to load the SDK from. This value is used for the "src" attribute of a dynamically added <script /> tag. You can use the public CDN location or your own privately hosted one.
name string [optional] The global name for the initialized SDK, defaults to appInsights. So window.appInsights will be a reference to the initialized instance. Note: if you provide a name value or a previous instance appears to be assigned (via the global name appInsightsSDK) then this name value will also be defined in the global namespace as window.appInsightsSDK=<name value>, this is required by the SDK initialization code to ensure it's initializing and updating the correct snippet skeleton and proxy methods.
ld number in ms [optional] Defines the load delay to wait before attempting to load the SDK. Default value is 0ms and any negative value will immediately add a script tag to the <head> region of the page, which will then block the page load event until to script is loaded (or fails).
useXhr boolean [optional] This setting is used only for reporting SDK load failures. Reporting will first attempt to use fetch() if available and then fallback to XHR, setting this value to true just bypasses the fetch check. Use of this value is only be required if your application is being used in an environment where fetch would fail to send the failure events.
crossOrigin string [optional] By including this setting, the script tag added to download the SDK will include the crossOrigin attribute with this string value. When not defined (the default) no crossOrigin attribute is added. Recommended values are not defined (the default); ""; or "anonymous" (For all valid values see HTML attribute: crossorigin documentation)
onInit function(aiSdk) { ... } [optional] This callback function which is called after the main SDK script has been successfully loaded and initialized from the CDN (based on the src value), it is passed a reference to the sdk instance that it is being called for and it is also called before the first initial page view. If the SDK has already been loaded and initialized this callback will still be called. NOTE: As this callback is called during the processing of the sdk.queue array you CANNOT add any additional items to the queue as they will be ignored and dropped. (Added as part of snippet version 5 -- the sv:"#" value within the snippet script, the current version is 6)
cfg object [required] The configuration passed to the Application Insights SDK during initialization.

Example using the snippet onInit callback

<script type="text/javascript">
!function(T,l,y){<!-- Removed the Snippet code for brevity -->}(window,document,{
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js",
crossOrigin: "anonymous",
onInit: function (sdk) {
  sdk.addTelemetryInitializer(function (envelope) {
    envelope.data.someField = 'This item passed through my telemetry initializer';
  });
}, // Once the application insights instance has loaded and initialized this method will be called
cfg: { // Application Insights Configuration
    connectionString: "YOUR_CONNECTION_STRING"
}});
</script>

Active Public CDN endpoints

To help with global resiliency, we have added and updated our primary CDN endpoint (source URL) so that if required we can address any outages without the need for everyone to update the URL used by the Application Insights snippet within their application.

All active CDN endpoints contain all of the previous (and future) versions of the SDK and there is currently no plans to stop or block accessing the snippet from the previous (legacy/backup) URL.

State CDN Endpoint Description
Primary https://js.monitor.azure.com/scripts/b/ai.2.min.js Provides additional resiliency, allowing us to redirect to a different CDN provider should there be an unexpected issue (if required).
Legacy/Backup
:exclamation: Deprecated
https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js Due to the legacy nature of this URL / Domain, if there is an unexpected issue (outage) with this domain, your application will need to be updated and deployed to use the new URL.
:exclamation: Due to #1813 this URL is now being classified as Deprecated and we will be actively making changes to the SDK to warnings in your telemetry if we detect this domain being used.

Connection String Setup

For either the NPM or Snippet setup, you can also configure your instance of Application Insights using a Connection String. Simply replace the instrumentationKey field with the connectionString field.

import { ApplicationInsights } from '@microsoft/applicationinsights-web'

const appInsights = new ApplicationInsights({ config: {
  connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE'
  /* ...Other Configuration Options... */
} });
appInsights.loadAppInsights();
appInsights.trackPageView();

(Alternative Setup Method) Include AI JS SDK script and initialize statically

Use this approach if you would like to host AI JS SDK script on your endpoint or bundle it with other scripts.

<!-- use your own path to JS SDK script -->
<script type="text/javascript" src="/pathToAIJSSDK.js"></script>

After JS script has loaded, include the following snippet to initialize Application Insights:

<!-- the snippet below assumes that JS SDK script has already loaded -->
<script type="text/javascript">
    var snippet = {
        config: {
            connectionString: "InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
        }
    };
    var init = new Microsoft.ApplicationInsights.ApplicationInsights(snippet);
    var appInsights = init.loadAppInsights();
    appInsights.trackPageView();
</script>

Sending Telemetry to the Azure Portal

If initialized using the snippet, your Application Insights instance is located by default at window.appInsights

appInsights.trackEvent({name: 'some event'});
appInsights.trackPageView({name: 'some page'});
appInsights.trackPageViewPerformance({name : 'some page', url: 'some url'});
appInsights.trackException({exception: new Error('some error')});
appInsights.trackTrace({message: 'some trace'});
appInsights.trackMetric({name: 'some metric', average: 42});
appInsights.trackDependencyData({absoluteUrl: 'some url', responseCode: 200, method: 'GET', id: 'some id'});
appInsights.startTrackPage("pageName");
appInsights.stopTrackPage("pageName", null, {customProp1: "some value"});
appInsights.startTrackEvent("event");
appInsights.stopTrackEvent("event", null, {customProp1: "some value"});
appInsights.flush();

Custom properties can be included in your telemetry through the properties named argument. This can be done with any of the Track APIs.

appInsights.trackEvent({
  name: 'some event',
  properties: { // accepts any type
    prop1: 'string',
    prop2: 123.45,
    prop3: { nested: 'objects are okay too' }
  }
});

Setting Up Autocollection

All autocollection is ON by default. The full version of the Application Insights Javascript SDK auto collects:

  • Uncaught exceptions in your app, including information on
    • Stack trace
    • Exception details and message accompanying the error
    • Line & column number of error
    • URL where error was raised
  • Network Dependency Requests made by your app XHR and Fetch (fetch collection is enabled by default) requests, include information on
    • Url of dependency source
    • Command & Method used to request the dependency
    • Duration of the request
    • Result code and success status of the request
    • ID (if any) of user making the request
    • Correlation context (if any) where request is made
  • User information (e.g. Location, network, IP)
  • Device information (e.g. Browser, OS, version, language, model)
  • Session information

Telemetry Initializers

Telemetry initializers are used to modify the contents of collected telemetry before being sent from the user's browser. They can also be used to prevent certain telemetry from being sent, by returning false. Multiple telemetry initializers can be added to your Application Insights instance, and they are executed in order of adding them.

The input argument to addTelemetryInitializer is a callback that takes a ITelemetryItem as an argument and returns a boolean or void. If returning false, the telemetry item is not sent, else it proceeds to the next telemetry initializer, if any, or is sent to the telemetry collection endpoint.

Example: Setting Cloud Role Name

var telemetryInitializer = (envelope) => {
  envelope.tags["ai.cloud.role"] = "your role name";
  envelope.tags["ai.cloud.roleInstance"] = "your role instance";
}
appInsights.addTelemetryInitializer(telemetryInitializer);

Example: Filtering

var telemetryInitializer = (envelope) => {
  envelope.data.someField = 'This item passed through my telemetry initializer';
};
appInsights.addTelemetryInitializer(telemetryInitializer);
appInsights.trackTrace({message: 'This message will use a telemetry initializer'});

appInsights.addTelemetryInitializer(() => false); // Nothing is sent after this is executed
appInsights.trackTrace({message: 'this message will not be sent'}); // Not sent

Dependency Listeners

A dependency listener is a callback function that allows you to perform additional manipulation of the request details before the request is performed.

This includes :-

  • Complete access to either the XMLHttpRequest instance or the fetch API input and init arguments.
  • Ability to get/set the properties used to generate the W3C traceparent header (traceId, spanId,traceFlags)
  • Set values in the object context container for other listeners called after the current one, as well as this context object is also made available to all dependency initializers.

Dependency Initializers

A Dependency Initializer is very similar to a Telemetry Initializer in that it allows you modify the contents of collected telemetry before being sent from the user's browser. And you can also returning false to cause the event to not be emitted.

The differences between a telemetry initializer and a dependency initializer are :-

  • A Dependency Initializer is called "before" the event is processed by the pipeline, as such it will NOT (yet) contain the automatically populated properties that are applied later;
  • When a dependency initializer returns false to drop the event the event does NOT count against the maxAjaxCallsPerView as this blocks the event call from being tracked, and while returning false from a Telemetry Initializer will also stop the event from being reported because this is further down the processing pipeline the dependency event IS counted against the maxAjaxCallsPerView limit.
  • It has access to an optional "context" { [key: string]: any } object that is also available to the Dependency Listeners. This allows a listener to add additional details to the context (before the XHR/fetch request is sent), and the initializer will be called after the request has completed.

Configuration

Most configuration fields are named such that they can be defaulted to falsey. All fields are optional except for instrumentationKey or a connectionString containing the instrumentation key.

Name Type Default Description
instrumentationKey string
[Required if connectionString not supplied]
null Instrumentation key that you obtained from the Azure Portal.
connectionString string
[Require if instrumentationKey not supplied]
null The Connection string that you obtained from the Azure portal
accountId string null An optional account id, if your app groups users into accounts. No spaces, commas, semicolons, equals, or vertical bars
sessionRenewalMs numeric 1800000 A session is logged if the user is inactive for this amount of time in milliseconds. Default is 30 minutes
sessionExpirationMs numeric 86400000 A session is logged if it has continued for this amount of time in milliseconds. Default is 24 hours
maxBatchSizeInBytes numberic 10000 Max size of telemetry batch. If a batch exceeds this limit, it is immediately sent and a new batch is started
maxBatchInterval numeric 15000 How long to batch telemetry for before sending (milliseconds)
disableExceptionTracking boolean | false If true, exceptions are not autocollected. Default is false.
disableTelemetry boolean false If true, telemetry is not collected or sent. Default is false.
enableDebug boolean false If true, internal debugging data is thrown as an exception instead of being logged, regardless of SDK logging settings. Default is false.
Note: Enabling this setting will result in dropped telemetry whenever an internal error occurs. This can be useful for quickly identifying issues with your configuration or usage of the SDK. If you do not want to lose telemetry while debugging, consider using loggingLevelConsole or loggingLevelTelemetry instead of enableDebug.
enableDebugExceptions boolean false Prior to v2.8.12 this was the only supported value and the documented enableDebug was incorrect, since v2.8.12 both enableDebug and enableDebugExceptions is supported. However, this configuration has been removed from v3.x
loggingLevelConsole numeric 0 Logs internal Application Insights errors to console.
0: off,
1: Critical errors only,
2: Everything (errors & warnings)
loggingLevelTelemetry numeric 1 Sends internal Application Insights errors as telemetry.
0: off,
1: Critical errors only,
2: Everything (errors & warnings)
diagnosticLogInterval numeric 10000 (internal) Polling interval (in ms) for internal logging queue
samplingPercentage numeric 100 Percentage of events that will be sent. Default is 100, meaning all events are sent. Set this if you wish to preserve your datacap for large-scale applications.
autoTrackPageVisitTime boolean false If true, on a pageview, the previous instrumented page's view time is tracked and sent as telemetry and a new timer is started for the current pageview. It is sent as a custom metric named PageVisitTime in milliseconds and is calculated via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less). Default is false.
disableAjaxTracking boolean false If true, Ajax calls are not autocollected. Default is false.
disableFetchTracking boolean false If true, Fetch requests are not autocollected. Default is false (Since v2.8.0, previously true)
excludeRequestFromAutoTrackingPatterns string[] | RegExp[] undefined Provide a way to exclude specific route from automatic tracking for XMLHttpRequest or Fetch request. If defined, for an ajax / fetch request that the request url matches with the regex patterns, auto tracking is turned off. Default is undefined.
addRequestContext (requestContext: IRequestionContext) => {[key: string]: any} undefined Provide a way to enrich dependencies logs with context at the beginning of api call. Default is undefined. You will need to check if xhr exists if you configure xhr related conetext. You will need to check if fetch request and fetch response exist if you configure fetch related context. Otherwise you may not get the data you need.
overridePageViewDuration boolean false If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. Default is false.
maxAjaxCallsPerView numeric 500 Default 500 - controls how many ajax calls will be monitored per page view. Set to -1 to monitor all (unlimited) ajax calls on the page.
disableDataLossAnalysis boolean true If false, internal telemetry sender buffers will be checked at startup for items not yet sent.
disableCorrelationHeaders boolean false If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. Default is false.
correlationHeaderExcludedDomains string[] undefined Disable correlation headers for specific domains
correlationHeaderExcludePatterns regex[] undefined Disable correlation headers using regular expressions
correlationHeaderDomains string[] undefined Enable correlation headers for specific domains
disableFlushOnBeforeUnload boolean false Default false. If true, flush method will not be called when onBeforeUnload event triggers
enableSessionStorageBuffer boolean true Default true. If true, the buffer with all unsent telemetry is stored in session storage. The buffer is restored on page load
cookieCfg ICookieCfgConfig
[Optional]
(Since 2.6.0)
undefined Defaults to cookie usage enabled see ICookieCfgConfig settings for full defaults.
isCookieUseDisabled
disableCookiesUsage
alias for cookieCfg.enabled
[Optional]
false Default false. A boolean that indicates whether to disable the use of cookies by the SDK. If true, the SDK will not store or read any data from cookies. isCookieUseDisable is deprecated in favor of disableCookiesUsage, when both are provided disableCookiesUsage take precedence.
(Since v2.6.0) If cookieCfg.enabled is defined it will take precedence over these values, Cookie usage can be re-enabled after initialization via the core.getCookieMgr().setEnabled(true).
cookieDomain alias for cookieCfg.domain
[Optional]
null Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains.
(Since v2.6.0) If cookieCfg.domain is defined it will take precedence over this value.
cookiePath alias for cookieCfg.path
[Optional]
(Since 2.6.0)
null Custom cookie path. This is helpful if you want to share Application Insights cookies behind an application gateway.
If cookieCfg.path is defined it will take precedence over this value.
isRetryDisabled boolean false Default false. If false, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error), 503 (service unavailable), and 0 (offline, only if detected)
isStorageUseDisabled boolean false If true, the SDK will not store or read any data from local and session storage. Default is false.
isBeaconApiDisabled boolean true If false, the SDK will send all telemetry using the Beacon API
disableXhr boolean false Don't use XMLHttpRequest or XDomainRequest (for IE < 9) by default instead attempt to use fetch() or sendBeacon. If no other transport is available it will still use XMLHttpRequest
onunloadDisableBeacon boolean false Default false. when tab is closed, the SDK will send all remaining telemetry using the Beacon API
onunloadDisableFetch boolean false If fetch keepalive is supported do not use it for sending events during unload, it may still fallback to fetch() without keepalive
sdkExtension string null Sets the sdk extension name. Only alphabetic characters are allowed. The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (e.g. 'ext_javascript:2.0.0'). Default is null.
isBrowserLinkTrackingEnabled boolean false Default is false. If true, the SDK will track all Browser Link requests.
appId string null AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. Default is null
enableCorsCorrelation boolean false If true, the SDK will add two headers ('Request-Id' and 'Request-Context') to all CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side. Default is false
namePrefix string undefined An optional value that will be used as name postfix for localStorage and session cookie name.
sessionCookiePostfix string undefined An optional value that will be used as name postfix for session cookie name. If undefined, namePrefix is used as name postfix for session cookie name.
userCookiePostfix string undefined An optional value that will be used as name postfix for user cookie name. If undefined, no postfix is added on user cookie name.
enableAutoRouteTracking boolean false Automatically track route changes in Single Page Applications (SPA). If true, each route change will send a new Pageview to Application Insights. Hash route changes changes (example.com/foo#bar) are also recorded as new page views.
enableRequestHeaderTracking boolean false If true, AJAX & Fetch request headers is tracked, default is false. If ignoreHeaders is not configured, Authorization and X-API-Key headers are not logged.
enableResponseHeaderTracking boolean false If true, AJAX & Fetch request's response headers is tracked, default is false. If ignoreHeaders is not configured, WWW-Authenticate header is not logged.
ignoreHeaders string[] ["Authorization", "X-API-Key", "WWW-Authenticate"] AJAX & Fetch request and response headers to be ignored in log data. To override or discard the default, add an array with all headers to be excluded or an empty array to the configuration.
enableAjaxErrorStatusText boolean false Default false. If true, include response error data text
enableAjaxPerfTracking boolean false Default false. Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics.
maxAjaxPerfLookupAttempts numeric 3 Defaults to 3. The maximum number of times to look for the window.performance timings (if available), this is required as not all browsers populate the window.performance before reporting the end of the XHR request and for fetch requests this is added after its complete.
ajaxPerfLookupDelay numeric 25 Defaults to 25ms. The amount of time to wait before re-attempting to find the windows.performance timings for an ajax request, time is in milliseconds and is passed directly to setTimeout().
distributedTracingMode numeric or DistributedTracingModes DistributedTracingModes.AI_AND_W3C Sets the distributed tracing mode. If AI_AND_W3C mode or W3C mode is set, W3C trace context headers (traceparent/tracestate) will be generated and included in all outgoing requests. AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services.
enableUnhandledPromiseRejectionTracking boolean false If true, unhandled promise rejections will be autocollected and reported as a javascript error. When disableExceptionTracking is true (dont track exceptions) the config value will be ignored and unhandled promise rejections will not be reported.
disableInstrumentationKeyValidation boolean false If true, instrumentation key validation check is bypassed. Default value is false.
enablePerfMgr boolean false [Optional] When enabled (true) this will create local perfEvents for code that has been instrumented to emit perfEvents (via the doPerf() helper). This can be used to identify performance issues within the SDK based on your usage or optionally within your own instrumented code. More details are available by the basic documentation. Since v2.5.7
perfEvtsSendAll boolean false [Optional] When enablePerfMgr is enabled and the IPerfManager fires a INotificationManager.perfEvent() this flag determines whether an event is fired (and sent to all listeners) for all events (true) or only for 'parent' events (false <default>).
A parent IPerfEvent is an event where no other IPerfEvent is still running at the point of this event being created and it's parent property is not null or undefined. Since v2.5.7
createPerfMgr (core: IAppInsightsCore, notificationManager: INotificationManager) => IPerfManager undefined Callback function that will be called to create a the IPerfManager instance when required and enablePerfMgr is enabled, this enables you to override the default creation of a PerfManager() without needing to setPerfMgr() after initialization.
idLength numeric 22 [Optional] Identifies the default length used to generate new random session and user id's. Defaults to 22, previous default value was 5 (v2.5.8 or less), if you need to keep the previous maximum length you should set this value to 5.
customHeaders [{header: string, value: string}] undefined [Optional] The ability for the user to provide extra headers when using a custom endpoint. customHeaders will not be added on browser shutdown moment when beacon sender is used. And adding custom headers is not supported on IE9 or earlier.
convertUndefined any undefined [Optional] Provide user an option to convert undefined field to user defined value.
eventsLimitInMem number 10000 [Optional] The number of events that can be kept in memory before the SDK starts to drop events when not using Session Storage (the default).
disableIkeyDeprecationMessage boolean true [Optional] Disable instrumentation Key deprecation error message. If true, error message will NOT be sent. Note: instrumentation key support will end soon, see aka.ms/IkeyMigrate for more details.
bufferOverride
since 2.8.12
IStorageBuffer undefined [Optional] Identifies a simple interface to allow you to override the storage mechanism used for tracking unsent and unacknowledged events, when not provided defaults to using SessionStorage interface. You MUST supply both the getItem and setItem functions when defined.
storagePrefix (since v2.8.15) string[] undefined [Optional] An optional value that will be added as name prefix for storage name. (design for system to correctly identifies these telemetry events as "necessary".)
retryCodes number[] undefined Identifies the status codes that will cause event batches to be resent, when null or undefined the SDK will use it's defaults [401, 408, 429, 500, 502, 503, 504]. 403 was removed in version 2.8.18.

ICookieMgrConfig

Cookie Configuration for instance based cookie management added in version 2.6.0.

Name Type Default Description
enabled boolean true A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance. If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies
domain string null Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. If not provided uses the value from root cookieDomain value.
path string / Specifies the path to use for the cookie, if not provided it will use any value from the root cookiePath value.
ignoreCookies string[] undefined Specify the cookie name(s) to be ignored, this will cause any matching cookie name to never be read or written. They may still be explicitly purged or deleted. You do not need to repeat the name in the blockedCookies configuration.(Since v2.8.8)
blockedCookies string[] undefined Specify the cookie name(s) to never be written, this will cause any cookie name to never be created or updated, they will still be read unless also included in the ignoreCookies and may still be explicitly purged or deleted. If not provided defaults to the same list provided in ignoreCookies. (Since v2.8.8)
getCookie (name: string) => string null Function to fetch the named cookie value, if not provided it will use the internal cookie parsing / caching.
setCookie (name: string, value: string) => void null Function to set the named cookie with the specified value, only called when adding or updating a cookie.
delCookie (name: string, value: string) => void null Function to delete the named cookie with the specified value, separated from setCookie to avoid the need to parse the value to determine whether the cookie is being added or removed.if not provided it will use the internal cookie parsing / caching.

From version 2.6.0, cookie management is now available directly from the instance and can be disabled and re-enabled after initialization.

If disabled during initialization via the disableCookiesUsage or cookieCfg.enabled configurations, you can now re-enable via the ICookieMgr setEnabled function.

The instance based cookie management also replaces the previous CoreUtils global functions of disableCookies(), setCookie(...), getCookie(...) and deleteCookie(...). And to benefit from the tree-shaking enhancements also introduced as part of version 2.6.0 you should no longer uses the global functions.

General Guidance

When calling getCookieMgr() before the SDK has successfully initialized will return a temporary ICookieMgr instance that will have cookie support fully enabled, thus allowing the getting, setting and deleting of cookies. So unless you know that your configuration WILL ALLOW cookie usage you should delay accessing or using the cookie manager until after initialization.

In v2.6.0 the getCookieMgr() is not directly available on the main entry points documented above for the snippet, NPM (ApplicationInsights) or React Plugin usages. As a workaround for this version you will need to access it via the core or appInsights properties as below (the getCookieMgr() will be available in later versions)

Snippet usage notes

The getCookieMgr() method, core and appInsights properties are only available AFTER the SDK has been successfully loaded and initialized.

So you will need to only call or access the manager from within the onInit() callback function (available in snippet (v5) or above) or after you know that the SDK has been loaded and initialized, otherwise you will cause an exception, unless you also perform an existence check of the property or function.

Additional Legacy snippet users for v2.6.0

If you are using a legacy snippet for your application (it is suggested that you upgrade), you will need to use the following options

Tree-Shaking Support and enhancements

As part of changes being introduced in version 2.6.0 we are deprecating and removing the internal usages of the static helper classes CoreUtils, EventHelper, Util, UrlHelper, DateTimeUtils and ConnectionStringParser to provide better support for tree-shaking algorithms so that unused code can be safely dropped when using NPM packages.

See Tree-Shaking Recommendations

Single Page Applications

By default, this SDK will not handle state based route changing that occurs in single page applications. To enable automatic route change tracking for your single page application, you can add enableAutoRouteTracking: true to your setup configuration.

Currently, we support a separate React plugin which you can initialize with this SDK. It will also accomplish route change tracking for you, as well as collect other React specific telemetry.

Source Map Support

The minified callstack of your exception telemetry can be unminified in the Azure Portal. All existing integrations on the Exception Details panel will work with the newly unminified callstack. Drag and drop source map unminifying supports all existing and future JS SDKs (+Node.JS), so you do not need to upgrade your SDK version. To view your unminified callstack,

  1. Select an Exception Telemetry item in the Azure Portal to view its "End-to-end transaction details"
  2. Identify which source maps correspond to this call stack. The source map must match a stack frame's source file, but suffixed with .map
  3. Drag and drop the source maps onto the call stack in the Azure Portal

Examples

For runnable examples, see Application Insights Javascript SDK Samples

Application Insights Web Basic

For a lightweight experience, you can instead install the basic version of Application Insights

npm i --save @microsoft/applicationinsights-web-basic

This version comes with the bare minimum amount of features and functionalities and relies on you to build it up as you see fit. For example, it performs no auto-collection (uncaught exceptions, ajax, etc). The APIs to send certain telemetry types, like trackTrace, trackException, etc, are not included in this version, so you will need to provide your own wrapper. The only api that is available is track. A sample is located here.

Available extensions for the SDK

Extensions NPM Version
Angular npm version
React npm version
React Native npm version

Upgrading from the old Version of Application Insights

Breaking changes in the SDK V2 version:

  • To allow for better API signatures, some of the apis such as trackPageView, trackException have been updated.
  • ES3 (IE8) compatibility, while running in IE8 or lower versions of the browser is not an officially supported scenario we are working to maintain ES3 level compatibility to ensure that the SDK will not cause any unexpected failures due to Javascript parsing error. See ES3/IE8 Compatibility below for further information.
  • Telemetry envelope has field name and structure changes due to data schema updates.
  • Moved context.operation to context.telemetryTrace. Some fields were also changed (operation.id --> telemetryTrace.traceID)
    • If you want to maunally refresh the current pageview id (e.g. in SPA apps) this can be done with appInsights.context.telemetryTrace.traceID = generateW3CId()

If you are using the current application insights PRODUCTION SDK (1.0.20) and want to see if the new SDK works in runtime, please update URL depending on your current SDK loading scenario:

a) Download via CDN scenario: Update code snippet that you currently use to point to the following URL:

```
"https://js.monitor.azure.com/scripts/b/ai.2.min.js"
```

b) NPM scenario: Call downloadAndSetup to download full ApplicationInsights script from CDN and initialize it with connection string.

appInsights.downloadAndSetup({
    connectionString: "InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
    url: "https://js.monitor.azure.com/scripts/b/ai.2.min.js"
});

Test in internal environment to verify monitoring telemetry is working as expected. If all works, please update your api signatures appropriately to SDK V2 version and deploy in your production environments.

Build a new extension for the SDK

The SDK supports the ability to include multiple extensions at runtime. In order to create a new extension, please implement the following interface:

ITelemetryPlugin

On initialization, config.extensions accepts an array of ITelemetryPlugin objects. These are hooked up and ITelemetryPlugin.processTelemetry() is chained based on priority of these plugins. Please note that higher the priority, the later your processing code will be invoked. The SDK supports a plugin model and channels can also be plugged in similarly (advanced scenario). Target scenarios for creating a brand new extension is to share a usage scenario that benefits multiple customers. Please follow guidelines

Here is the priority ranges available:

  • Regular extension priority can be between 201 to 499.
  • Priorty range < 201 is reserved.
  • Priority range > 1000 is for channels (advanced scenario)

BaseTelemetryPlugin

To help with the creation of new extensions there is now a supported base class which can be used, this not only provides the common (boilerplate) implementations of common functions it will enable future plugins to automatically receive functional updates with the need to recode the plugins. it provides implementations for :-

  • ITelemetryPlugin.setNextPlugin() implementation to continuing supporting existing (non-shared) execution of plugins, however, new plugins should use the new IProcessTelemetryContext.processNext() moving forward as this support the creation of shared (singleton) plugins;
  • New ITelemetryPlugin.isInitialized() implementation
  • And several helper methods.

    If you are creating new extensions it is recommended that you extend from this base class so that your extension will automatically inherit any future enhancements that are added to the ITelemetryPlugin interface without it requiring updates.

Usage:

const customPluginInstance = new YourCustomPlugin()
const appInsights = new ApplicationInsights({ config: {
    connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
    extensions: [customPluginInstance]
    // Other Configuration Options...
}});
appInsights.loadAppInsights();

ITelemetryPlugin has a simpler base type IPlugin that you can instantiate for initialization purposes when SDK loads.

Build & Test this repo

  1. Install all dependencies

     npm install
     npm install -g @microsoft/rush
  2. Navigate to the root folder and update rush dependencies

     rush update
  3. Build and test

     rush build
     npm run test

Performance

Application Insights JS adds a negligible amount of load time to your website. By using the snippet, minimal components of the library are quickly loaded. In the meantime, the full script is downloaded in the background.

While the script downloads from the CDN, all tracking of your page is queued. Once the downloaded script finishes asynchronously initializing, all events that were queued are tracked. As a result, you will not lose any telemetry during the entire life cycle of your page. This setup process provides your page with a seamless analytics system, invisible to your users.

Summary:

  • current npm version
  • gzip compressed size
  • ~15 ms overall initialization time
  • Zero tracking missed during life cycle of page

Module Formats

As part of packaging we produce umd (Universal Module Definition) modules using rollupjs which creates a wrapper that works for most users as it supports module loading and initialization with or without RequireJS.

However, there are some cases where your code doesn't directly use RequireJS but it is loaded into the runtime environment before your code and the 1DS SDK, in these cases the rollupjs wrapper registers (defines) but does not initialize (execute) the SDK and instead waits for the first to call "require()" before the module is executed

eg. var aiSdk = require("@microsoft/applicationinsights-web");

This situation can also occur when the scripts are loaded lazily, late or dynamically (and RequireJs is present) as this can cause a race condition between the SDK and RequireJS, which will cause the same issue if RequireJS is loaded first.

To support this usage pattern we also produce and publish to the CDN endpoints an iife (Immediately Invoked Function Expression) module so that the SDK is always executed and initialized.

To use these modules instead of using the default script name simply add .gbl before the .min.js eg. use .gbl.min.js instead of .min.js at the end of the script name.

These modules are also included in the NPM packages within the bundle folder.

Example (not complete) CDN paths for the current major version.

Module Default Module IIFE Module
AISku
(Main Sdk)
http://js.monitor.azure.com/scripts/b/ai.2.min.js http://js.monitor.azure.com/scripts/b/ai.2.gbl.min.js
Click Analytics Extension http://js.monitor.azure.com/scripts/b/ext/ai.clck.2.min.js http://js.monitor.azure.com/scripts/b/ext/ai.clck.2.gbl.min.js
Debug Plugin Extension http://js.monitor.azure.com/scripts/b/ext/ai.dbg.2.min.js http://js.monitor.azure.com/scripts/b/ext/ai.dbg.2.gbl.min.js
Perf Mark/Measure Manager Extension http://js.monitor.azure.com/scripts/b/ext/ai.prfmm-mgr.2.min.js http://js.monitor.azure.com/scripts/b/ext/ai.prfmm-mgr.2.gbl.min.js

As part of the CDN deployment and promoting new versions as the default we also provide both minor and explicit versions of all modules, so each published module will also include the following versions and formats. The example names are assuming version 3 as the current major version and 3.1 and the current minor.

Major Minor Patch (Explicit) Description
ai.2.min.js ai.2.7.min.js ai.2.7.2.min.js Minified UMD version
ai.2.gbl.min.js ai.2.7.gbl.min.js ai.2.7.2.gbl.min.js Minified IIFE version

And the process of Promoting (or rolling back) a deployed version is simply a case of replacing the major and minor version of the script with the current explicit version

CDN Debugging support

We support 2 basic approaches for debugging the SDK via the CDN hosted scripts

  • Every Module includes a //# sourceMappingURL=xxxx at the end of the file and has the referenced map file uploaded to the CDN.
  • We also publish unminified versions of every module, just drop the .min from the script name (eg. https://js.monitor.azure.com/scripts/b/ai.2.js)
Major Minor Patch (Explicit) Description
ai.2.min.js.map ai.2.7.min.js.map ai.2.7.2.min.js.map Map file for the UMD versions
ai.2.gbl.min.js.map ai.2.7.gbl.min.js.map ai.2.7.2.gbl.min.js.map Map file for the IIFE versions
ai.2.js ai.2.7.js ai.2.7.2.js Unminified UMD versions
ai.2.gbl.js ai.2.7.gbl.js ai.2.7.2.gbl.js Unminified IIFE versions

Nightly Builds

To aid with testing and validation we also produce and publish nightly builds whenever there is a change from the previous build. These builds are published to the NpmJs registry and to the CDN automatically on a successful build / test pass.

This process also tags the source code so that we can track the specific changes included using a nightly build specific version number which is the format "nightly-yymm-##" eg. nightly-2112-08

These nightly builds will not be retained indefinitely and should only be used for pre-production testing and/or validation of any changes that have not yet been released.

NPM

The NPM builds are tagged as "nightly" and can by downloaded using this as the version number npm install @microsoft/applicationinsights-web@nightly or using the nightly specific version number which is "nightly.yyyymm-###" (npm install @microsoft/applicationinsights-web@2.7.3-nightly.2112-08) where ## is the specific build number for the month (Note, slightly different version from the source code tag due to compatibility issues between the different systems).

CDN

These nightly builds are also uploaded to a different path on the CDN and explicitly have the -nightly added to the module name eg. /nightly/ai.2-nightly.min.js, each nightly build is re-numbered assuming the next release will be a patch release. So if the last release was 2.7.2, then all nightly builds will be numbered 2.7.3-nightly.

So to access simply update the URL used when downloading the required module.

Module Nightly Build
AISku (Main Sdk) http://js.monitor.azure.com/nightly/ai.2-nightly.min.js
Click Analytics Extension http://js.monitor.azure.com/nightly/ext/ai.clck.2-nightly.min.js
Debug Plugin Extension http://js.monitor.azure.com/nightly/ext/ai.dbg.2-nightly.min.js
Perf Mark/Measure Manager Extension http://js.monitor.azure.com/nightly/ext/ai.prfmm-mgr.2-nightly.min.js

As with the normal release process the nightly builds also include major, minor, explicit, IIFE (.gbl), *.map and unminified versions, these are primarily available for validating changes between builds.

Module CDN Path
Major http://js.monitor.azure.com/nightly/ai.2-nightly.min.js
http://js.monitor.azure.com/nightly/ai.2-nightly.gbl.min.js
http://js.monitor.azure.com/nightly/ai.2-nightly.js
http://js.monitor.azure.com/nightly/ai.2-nightly.gbl.js
Minor http://js.monitor.azure.com/nightly/ai.2.7-nightly.min.js
http://js.monitor.azure.com/nightly/ai.2.7-nightly.gbl.min.js
http://js.monitor.azure.com/nightly/ai.2.7-nightly.js
http://js.monitor.azure.com/nightly/ai.2.7-nightly.gbl.js
Explicit http://js.monitor.azure.com/nightly/ai.2.7.3-nightly.2112-08.min.js
http://js.monitor.azure.com/nightly/ai.2.7.3-nightly.2112-08.gbl.min.js
http://js.monitor.azure.com/nightly/ai.2.7.3-nightly.2112-08.js
http://js.monitor.azure.com/nightly/ai.2.7.3-nightly.2112-08.gbl.js

Deployment process and alternate CDN endpoints

When a new release is deployed the following occurs as part of the release

  • NPM packages are created and published to NpmJs
  • The new explicit versioned files (eg. ai.2.7.2.js; ai.2.7.2.min.js; ai.2.7.2.gbl.min.js; ai.2.7.2.min.js.map; etc) are uploaded to all cdn endpoints URL's (public, next and beta - details below)
  • We then go through a deployment process of "promoting" the new version to the "Major" (ai.2.min.js) and "Minor" (ai.2.x.min.js) release URL's to upgrade everyone to the newly released version based on the schedule listed below
Endpoint Url Schedule
Beta https://js.monitor.azure.com/beta/ai.2.min.js Same day as the NPM release
Next https://js.monitor.azure.com/next/ai.2.min.js One additional work day after the beta URL promotion.
Public https://js.monitor.azure.com/scripts/b/ai.2.min.js Another One additional work day after the next URL promotion, (so 2 work days after initial release) unless this falls on the last work day of the week (eg. Friday) in which case it will be delayed until the first work day of the next work week.

The milestones for each release should include both the deployment plan (as it's about to be released) or the final release times as with v2.7.2

It is expected that most users will be using the Public URL, however, it is also recommended that if you have a test or canary environment that you should use either the beta or next URL's so that you would be alerted first before any production users are impacted. If any issues are detected with the beta or next URL's as a new release is being deployed please raise a new Issue as soon as this is confirmed.

Release Notes

Browser Support

Chrome Firefox IE Opera Safari
Latest ✔ Latest ✔ 9+ Full ✔
8- Compatible
Latest ✔ Latest ✔

Note: ES3/IE8 compatibility will be removed in the future v3.x.x releases (scheduled for mid-late 2022), so if you need to retain ES3 compatibility you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK.

Build and Test this Project

Note: With the recent update to the latest version of rush npm run build fails with exit code 1 on successful build, hence the addition of --silent to the npm run build command.

npm install -g @microsoft/rush
npm install
npm run build --silent

Submitting a Change to this Project

<...added some code...>
rush change
<...enter details>
git add <...your changes and rush change file...>
git commit -m "info about your change"
git push

ES3/IE8 Compatibility

Future releases of the SDK numbered v3.x.x will be removing ES3 (IE8) support, so if you need to retain ES3 compatibility for your environment you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK.

As an SDK there are numerous users which cannot control the browsers that their customers use. As such we need to ensure that this SDK continues to "work" and does not break the JS execution when loaded by an older browser. While it would be ideal to just not support IE8 and older generation (ES3) browsers there are numerous large customers/users that continue to require pages to "work" and as noted they may or cannot control which browser that their end users choose to use.

This does NOT mean that we will only support the lowest common set of features, just that we need to maintain ES3 code compatibility and when adding new features they will need to be added in a manner that would not break ES3 Javascript parsing and added as an optional feature.

As part of enabling ES3/IE8 support we have set the tsconfig.json to ES3 and uglify settings in rollup.config.js transformations to support ie8. This provides a first level of support which blocks anyone from adding unsupported ES3 features to the code and enables the generated javascript to be validily parsed in an ES3+ environment.

Ensuring that the generated code is compatible with ES3 is only the first step, JS parsers will still parse the code when an unsupport core function is used, it will just fail or throw an exception at runtime. Therefore, we also need to require/use polyfil implementations or helper functions to handle those scenarios.

It should also be noted that the overall goal of ES3/IE8 compatibility is the support at least the following 2 usage usage patterns. By supporting these two (2) basic use-cases, application/developers will be able to determine what browsers their users are using and whether they are experiencing any issues. As the SDK will report the data to the server, thus enabling the insights into whether they need to either fully support ES3/IE8 or provide some sort of browser upgrade notifications.

  • track()
  • trackException()

Beyond terminating support for older browsers that only support ES3, (which we cannot do at this point in time) we will endeavour to maintain support for the above two (2) use-cases.

Browser must support JSON class

If your users are using a browser that does not support the JSON Api you will need to include your own JSON polyfil implementation and this will need to be loaded prior to the application insights code.

This includes when running your application within an embedded browser, which on windows will default to using IE in IE7 doc mode -- which does NOT provide the JSON Api.

For this case either provide a JSON polyfil or add the "X-UA-Compatible" meta tag and/or a header to your hosting page so that IE will provide the expected runtime environment.

 <meta http-equiv="X-UA-Compatible" content="IE=edge">

 <meta http-equiv="X-UA-Compatible" content="IE=11">

More details on this are available here

ES3/IE8 Packaging helper (ES3 rollup-plugin)

To ensure that the system conforms to the ES3 spec, by only using ES3 compatible code we have created a rollup plugin which has 2 functions

  • es3Poly() finds and rewrite several commonly incompatible functions (such as Object.defineProperty; Object.getOwnPropertyDescriptor; Object.create) with inline polyfill functions that either call the real implementation or provide a basic implementation so that the scripts can be loaded and executed.
  • es3Check() finds some of the known ES3 incompatible methods and will stop the packaging process if they are identified (and have not been polyfilled by es3Poly()), this provides a semi-automated validation of not just the application insights code, but also 3rd party libraries that it uses.
  • importCheck() checks that the source code does not include imports from specific files or packages, this has been added due to packaging issues while using es3Poly causing imported type values to be renamed as "name$$1", which causes uglify() to missing renaming in some cases where the original source is "name$1". So this is being used to ensure that each source file only imports the values from packages or the original source file and not the main module export like "index". The importCheck can be placed before the nodeResolve() or after the es3Check() the recommendation is to fail fast be having this before the resolve. It should also be noted that only if the import is used will it appear in the final output (packagin), so it may exist in the original source but the packaging will not fail in this case.

To use these rollup plugins you simply need to add the following to your rollup.config.js

To import the module

import { es3Poly, es3Check, importCheck } from "@microsoft/applicationinsights-rollup-es3";

And then include as part of the packaging plugin list, if you use es3Poly()you should always include it before es3Check()

    plugins: [
      replace({ ... }),
      importCheck({ exclude: [ "Index" ] }),
      nodeResolve({ browser: false, preferBuiltins: false }),
      es3Poly(),
      es3Check()
    ]

All plugins take an options which allows you to add additional checks and polyfill replacements. See the Interfaces.ts for the definitions and ES3Tokens.ts for the default values, which should provide the examples, if we have missed some common values that you require please feel free to raise an issue or provide a PR to add as the defaults.

It should be noted at this point that the both react and react-native extensions will NOT work in an ES3/IE8 environment out of the box, primarily because of the react code and their dependencies. You may be able to workaround this limitation by providing and your own polyfill implementations for the unsupported methods.

ES3/IE8 Features, Solutions, Workarounds and Polyfill style helper functions

Note: We will be removing our internal ES3 / IE8 support polyfills as part of the next major release 3.x.x (scheduled for mid-late 2022), so if you need to retain ES3 compatibility you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK.

As part of contributing to the project the following table highlights all of the currently known issues and the available solution/workaround. During PR and reviewing please ensure that you do not use the unsupported feature directly and instead use (or provide) the helper, solution or workaround.

This table does not attempt to include ALL of the ES3 unsupported features, just the currently known functions that where being used at the time or writing. You are welcome to contribute to provide additional helpers, workarounds or documentation of values that should not be used.

Feature Description Helper, Solution or Workaround
JSON.stringify(obj) We have a hard requirement on JSON support, however, because of the size of adding a specific JSON polyfil just for our usage we decided not to include our own version. As such any user of this Api MUST include a JSON polyfil implementation, otherwise, the API simply will not work. App/Site MUST provide their own JSON polyfil.
Object.keys() Not provided by ES3, use the helper CoreUtils.objKeys(obj: {}): string[]
ES5+ getters/setters
Object.defineProperty(...)
Code will needs to created the individual getters/setters manually in a static initializer. See ChannelController.ts for example usage.
However, to ensure compatibility actual usage of any getters/setters internally in the primary SDK code is not permitted. They may (and should) be used in unit tests to ensure that if used they function as expected (in an ES5+ environment).
CoreUtils.objDefineAccessors<T>(target:any, prop:string, getProp?:() => T, setProp?: (v:T) => void) : boolean
Object.create(protoObj) Not supported in an ES3 environment, use the helper or direct construct the object with SON style notation (if possible) CoreUtils.objCreate(obj:object):any
Object.create(protoObj, descriptorSet) Not supported and no provided workaround/solution. N/A
Object.defineProperties() Not supported and no provided workaround/solution. N/A
Object.getOwnPropertyNames(obj) Not supported and no provided workaround/solution. N/A
Object.getPrototypeOf(obj) Not supported and no provided workaround/solution. N/A
Object.getOwnPropertyDescriptor(obj) Not supported and no provided workaround/solution. N/A
Object.getOwnPropertyNames() Not supported and no provided workaround/solution. N/A
Object.preventExtensions(obj) Not supported and no provided workaround/solution. N/A
Object.isExtensible(obj) Not supported and no provided workaround/solution. N/A
Object.seal(obj) Not supported and no provided workaround/solution. N/A
Object.isSealed(obj) Not supported and no provided workaround/solution. N/A
Object.freeze(obj) Not supported and no provided workaround/solution. N/A
Object.isFrozen(obj) Not supported and no provided workaround/solution. N/A
Array.prototype.indexOf(...) Use the provided helper CoreUtils.arrIndexOf<T>(arr: T[], searchElement: T, fromIndex?: number): number
Array.prototype.lastIndexOf(...) Not supported and no provided workaround/solution. N/A
Array.prototype.every(...) Not supported and no provided workaround/solution. N/A
Array.prototype.some(...) Not supported and no provided workaround/solution. N/A
Array.prototype.forEach(...) Use the provided helper. arrForEach<T>(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => void, thisArg?: any):void
Array.prototype.map(...) Use the provided helper. CoreUtils.arrMap<T,R>(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => R, thisArg?: any): R[]
Array.prototype.filter(...) Not supported and no provided workaround/solution. N/A
Array.prototype.reduce(...) Use the provided helper. `CoreUtils.arrReduce<T,R>(arr: T[], callbackfn: (previousValue: T
Array.prototype.reduceRight(...) Not supported and no provided workaround/solution. N/A
Date.prototype.toISOString() Use the provided helper CoreUtils.toISOString(date: Date)
Date.now() Use the provided helper CoreUtils.dateNow()
performance.now() Use the provided helper for the Performance Api now function. CoreUtils.perfNow()

Contributing

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Application Insights.

Data Collection

As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement.

The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.

License

MIT

changelog

Releases

Note: ES3/IE8 compatibility will be removed in the future v3.x.x releases (scheduled for mid-late 2022), so if you need to retain ES3 compatibility you will need to remain on the 2.x.x versions of the SDK or your runtime will need install polyfill's to your ES3 environment before loading / initializing the SDK.

2.8.17 (Mar 12th, 2024)

Changelog

  • 2296 [BUG] remove 403 as a “retriable” error code

  • 2280 [Master] chore: Add packaging helper script

2.8.17 (Feb 6th, 2024)

Changelog

  • 2163 [Master] [BUG] Using App Insights connection string leads to double slash

  • 2260 [Master] Bump @microsoft/dynamicProto-js to ^1.1.11 from ^1.1.9

    • Addresses a potential prototype pollution issue

2.8.16 (Sep 19th, 2023)

Changelog

  • 2155 [Master] Bug [AI/1DS] New minified bundles are corrupting global scope (p1 issue)

  • 2151 Bug 25182794: [AI] Minified CDN version has an extra "use strict" outside of the closure

  • 2120 Missing traceparent header when running multiple SDK instances

    • 2140 [Master][Bug] Missing traceparent header when running multiple SDK instances #2120

    • 2143 [Master][Part 2] Missing traceparent header when running multiple SDK instances #2120

  • 2149 [BUG] Fetch with empty string as first parameter ignores second parameter when fetch tracking is enabled

    • 2154 [Master][BUG] Fetch with empty string as first parameter ignores second parameter when fetch tracking is enabled #2149

  • 2128 [Master] Update publishing config to avoid resetting the "latest" version for older releases

2.8.15 (Aug 3rd, 2023)

Changelog

  • 2100 Update UMD and IIFE Bundle intro for Version 2 to avoid conflicting with other SDK versions

  • 2106 [Master] Consider export IClickAnalyticsConfiguration from the click plugin?

  • 2107 [Master][Task]24316375: add support for cfgSync plugin

  • 2086 [BUG] Field 'fileName' on type 'StackFrame' is too long. Expected: 1024 characters

  • 2094 _getVerifiedStorageObject - contentious sessionStorage element

  • 2096 [Master] Create rollup base to unify bundling

    • 2122 [Master] base rollup fix for version number

2.8.14 (May 22nd, 2023)

Changelog

  • 2061 [BUG] hasDocument should be invoked as function

  • 2079 [Master] [BUG] The SDK is not limiting the sdkVersion length, which causes the nightly builds to throw error

  • 2065 [Master] Type 'T' does not satisfy the constraint 'IConfiguration'

  • 2075 [Master] [BUG] ClickAnalytics throwing errors in console

  • 2071 [Master] Update Minify script to always sort imports

2.8.13 (May 1st, 2023)

Changelog

  • 2052 [BUG] Typing issue with generated types causing Type X is not assignable to type Y

  • 2055 Add ability to disable the pollInternalLogs via config and change to stop using setInterval

  • 2049 [Master] Fix Perf Tests

2.8.12 (Apr 11th, 2023)

Changelog

  • 2014 [BUG] The documentation for enableDebug is incorrect, it should reference enableDebugExceptions

  • 2027 [BUG] SDK LOAD Failure reporting not working

  • 2034 [BUG] Failed XHR request after ever tracked item when gathered logs exceed maxBatchSizeInBytes while offline

  • 2037 [Master] Add local storage-based implementation #1419

    • Add support for user provided storage option for Sender
  • 2029 [Master] Add npm-pack and npm-publish tasks

  • 2026 [Master] Fix examples, Throttle tests and export dependency types from Sku

2.8.11 (Mar 8th, 2023)

Changelog

  • 1996 [BUG] SharedWorker does not Instrument fetch correctly

  • 1995 [BUG] App Insights not auto-capturing from a Web Worker

    • Stops logging that workers can emit the PageView Performance event
  • 1792 [BUG] Documentation should clarify that node apps should use applicationinsights, not this package

  • 1794 [BUG] link on AISKULight goes to not found page

  • 1990 Field 'assembly' on type 'StackFrame' is too long. Expected: 1024 characters [BUG]

  • Update documentation and tests to replace instrumentationKey usage with connectionString
    • 1997 Change Readme

    • 1999 Add snippet connection string tests

  • 1991 Internal Task 17133116: Add Policheck exclusion file

  • 1989 [AI][Task]17099792: Add sample and doc to dependency plugin

2.8.10 (Feb 6th, 2023)

Changelog

  • 1940 [BUG] Application Insights reports 'not_specified' to Azure when tracking unhandled browser exception

  • 1979 [BUG][ThrottleMgr] Incorrectly fires based on the number of days past

  • 1970 Add the Aborted flag to the dependency initializer / listeners

  • 1981 [AI][Task]16961420: fix throttleMgr incorrectly fires based on the number of days past

  • 1956 [AI Light][Task]14130466: Instrumentation key API is being deprecated - need to add support

  • 1962 Add --no-sandbox to test runs

2.8.9 (Oct 25th, 2022)

  • Updates Chrome Debug Extension to 0.3.9

Changelog

  • 1920 Update to DynamicProto v1.1.7

  • 1935 Update to @microsoft/applicationinsights-shims: 2.0.2

    • 1911 Uncaught ReferenceError: global is not defined

  • 1912 Update PerfTests to use the latest version

  • 1916 [Bug] Fix randomly failing tests

  • 1915 Fix CodeQL Identified potential Issues

  • 1906 [Task]14569737: add throttle cdn config

  • 1930 Remove the source-map-loader from the package.json as we don't use it.

Shims 2.0.2 (Oct 24th, 2022)

Changelog

  • 1911 Uncaught ReferenceError: global is not defined

2.8.8 (Oct 3rd, 2022)

  • Updates Chrome Debug Extension to 0.3.8

Changelog

  • 1679 [BUG] enableUnhandledPromiseRejectionTracking shows no error trace

    • 1900 [Task]15465575: add getErrorstackObj from reason.stack

  • 1901 [Feature] Add option to block the creation and usage of the cookies by name

  • 1904 Fixed release notes, previously used a deprecated file.

2.8.7 (Sept 7th, 2022)

  • Updates Chrome Debug Extension to 0.3.7

Changelog

  • 1863 [BUG]urlCollectQuery not work for applicationinsights-clickanalytics-js

    • 1874 Add clickanalytics plugin url config back

  • 1875 [BUG] error thrown using basic version + NPM setup

    • fix(AISKULight): call getSKUDefaults after it's defined, change this
  • 1878 [JS SDK] Update Retry logic to handle additional response codes

  • 1890 [BUG] Behavior difference for an empty endpointUrl when upgrading from v1 to v2

  • 1895 Fix incorrect disableFetchTracking documentation

  • 1887 maxAjaxCallsPerView doesn't account for filtering by TelemetryInitializer

    • adds addDependencyInitializer()

2.8.6 (Aug 2nd, 2022)

  • React plugin is now located and released from it's own repo
  • React Native plugin is now located and released from it's own repo
  • Updates Chrome Debug Extension to 0.3.6

Changelog

  • 1862 [BUG] Remote Dependency requests don't "always" have the correct ai.operation.id tag (page view race condition)

  • 1870 [BUG] Performance improvements when calling newGuid multiple times (like 10,000)

  • 1865 Update and add legal compliance notices and license terms

  • 1866 Remove React-JS and React-Native code from this repo

2.8.5 (Jul 6th, 2022)

  • Updates React Plugin to v3.3.5 (with v2.8.5 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.5 (with v2.8.5 as dependency)
  • Updates Chrome Debug Extension to 0.3.5

Changelog

  • 1636 [BUG] measurements not being sent when using stopTrackEvent(name, properties, measurements);

  • 1857 [BUG] CDN Packaging is not exposing the internal tools (CoreUtils / Telemetry / etc)

    • This was caused by the updated tree-shaking component that we used, fixing this has increased the CDN payload but it provides backward compatibility again
  • 1852 [BUG] Snippet initialization with IE8 fails with minified code (works with un-minified code)

    • This was specific to IE8 usages
  • 1076 Refactor code to provide better tree shaking and minification of generated code

    • Final stage which provides automatic name crunching, however, because of the fix for #1857 the CDN package size does not show the full effect of this improvement
  • 1860 Address Component Governance issues

2.8.4 (Jun 1st, 2022)

  • Updates React Plugin to v3.3.4 (with v2.8.4 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.4 (with v2.8.4 as dependency)
  • Updates Chrome Debug Extension to 0.3.4

Changelog

  • 198 Run-time Telemetry initializers for Ajax requests

  • 176 Single Page Application Page View Tracking

  • 1776 How to modify traceflag in traceparent header?

  • 1846 Task 7496325: Add Distributed tracing population for the properties for the core

  • 1838 [master] Task 14447552: Fix Component Governance vulnerabilities

  • 1841 Adding Microsoft SECURITY.MD

  • 1845 add readme for ikey error messge

  • 1840 add disableIkeyMessage config

2.8.3 (May 3rd, 2022)

  • Updates React Plugin to v3.3.3 (with v2.8.3 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.3 (with v2.8.3 as dependency)
  • Updates Chrome Debug Extension to 0.3.3

This release has been manually validated to work with IE8 both directly and by extending the provided classes. While the previous version 2.8.2 also fully supported IE8 it did not handle classes extending the all of Core classes correctly in multiple cases. If you need to support IE8 it is strongly advised that you upgrade to, validate and use this version.

Changelog

  • 1831 Updates to dynamicProto() v1.1.6 which provides a final edge case fix for IE8

    • #50 [IE8] Fix in 1.1.5 only handles 2 levels of dynamically nested classes
  • 1828 Update README.md to redirect to Node.JS

  • 1829 Extracting HOC tracked component class base for re-use

  • 1804 [BUG] Error type in AppInsightsErrorBoundary after upgrading to react 18

2.8.2 (May 2nd, 2022)

  • Updates React Plugin to v3.3.2 (with v2.8.2 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.2 (with v2.8.2 as dependency)
  • Updates Chrome Debug Extension to 0.3.2

This patch release restores complete ES3 support (broken in 2.8.0) and IE8 support (broken eariler via dynamicProto()) for the Sdk.

Changelog

  • 1822 [BUG] v2.8.1 with a Hosted IE environment fails to initialize for a hosted instance of IE #1822 (#1824)

  • 1823 [BUG] IE8 Support was broken by several components #1823

  • Also updates to dynamicProto() v1.1.5 to restore IE8 support

2.8.1 (Apr 22nd, 2022)

  • Updates React Plugin to v3.3.1 (with v2.8.1 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.1 (with v2.8.1 as dependency)
  • Updates Chrome Debug Extension to 0.3.1

This patch release restores TypeScript 3.x support for the Sdk.

Changelog

  • 1807 [BUG] Angular project doesn't build after install latest version v.2.8.0

  • 1810 v2.8.0 has incompatible TypeScript 3.x type declaration

  • 1812 [BUG] Browser exceptions are no longer automatically tracked after 2.8.0

  • 1814 [BUG]SPFx React project doesn't build after latest version of @microsoft/application-insights-core-js v.2.8.0 got published

2.8.0 (Apr 16th, 2022)

  • Updates React Plugin to v3.3.0 (with v2.8.0 as dependency) -- using React 17
  • Updates React Native Plugin to 2.5.0 (with v2.8.0 as dependency)
  • Updates Chrome Debug Extension to 0.3.0

Potential Breaking Change

  • fetch Ajax tracking was also been change to be on by default from this version moving forward, if you are running in an environment without fetch support and you are using an incompatible polyfill (that doesn't identify itself as a polyfill) or the SDK you start seeing recursive or duplicate (fetch and XHR requests) being reported you WILL need to add disableFetchTracking with a value of true to your configuration to disable this functionality.
  • TypeScript 4.x required for some typings from the core EnumHelperFuncs.d.ts (Fixed in v2.8.1)

Significant changes

This release adds support for the SDK to

  • TelemetryInitializers have been moved to BaseCore so they are now available as part of all Sku's and not just those using the analytics plugin (@microsoft/applicationinsights-analytics-js) using the appInsights.addTelemetryInitializer(...)
  • Web Events (addEventHandler) now support "event namespaces" (similar to jQuery) to enable the removing of events by just specifying the namespace and new specific eventOn(...) and eventOff(...) API's.
  • Fully unload, removing all internal event handlers (may be re-initialized) via the appInsights.unload(...) function.
  • Dynamically add a plugin to an already initialized SDK (optionally replacing an existing) via new appInsights.addPlugin(...) function
  • New helper to get any plugin from an initialized SDK via appInsights.getPlugin("...identifier...")
  • Dynamically remove a plugin via the appInsights.getPlugin("...identifier..").remove()
  • Enable / Disable any plugin (even if the plugin doesn't support disabling itself) via appInsights.getPlugin("...identifier...").setEnabled(true/false)
  • The standard name fro the analytics plugin @microsoft/applicationinsights-analytics-js has been renamed and is now exported as AnalyticsPlugin, for backward compatibility it is also exported as it's previous name ApplicationInsights, if you are using it directly it is recommended that you update to use the new exported name.

While this release contains a substantial amount of additional functionality and code, there has also been significant minification efforts (which also drove some of the SDK naming) to keep the minified code around the same size. We intend to keep working on additional improvements to attempt to bring the size changes down further. However, the minification improvements do generally cause a lower level of GZip compression most because of the removal of duplicate names. The main readme for the AISKU has a table of the CDN base SKU sizes, as the CDN version includes all public API's (older versions for backward compatibility and newer smaller versions) when using NPM you should see smaller sizes than those shown.

Note: Due to the above changes required to support the above, there may be some minor TypeScript Type compatibility warnings when you attempt to use components from v2.8.0 with older SDK's (forward compatibility), backward compatibility, using Core v2.8.0 with older components is supported and v2.8.0 is completely backward compatible. This is due to some API's now support both older (for back compat) and new enhanced arguments, we have attempted to keep these changes to a minimum. If you are getting typing errors such as "Argument of type 'XXXXX' os not assignable to parameter of type 'YYYY'", please ensure that you are using all v2.8.0 components and raise an issue if this does not resolve you issue. As a work around casting to work around this warning should not cause any issues.

Due the the size of this change, the above date is the NPM release date and CDN deployment will be over an extended period.

Changelog

  • Task 13064945: Enable the option to remove all "added" SDK event listeners as part of calling teardown()
    • Partial, foundational support for #1427 Dynamically updating config (for extensions in my case)
  • 1773 [BUG] IConfig and IConfiguration define different configuration "names" for the cookie manager config

  • 1779 Allow including custom properties in useTrackMetric

  • 1791 Merge remote-tracking branch upstream/beta into master

    • Update version update script to support default "next" release version (major/minor) not just patch (#1756)
    • Additional Performance enhancements to use provided functions rather than internal polyfill's (#1758)
    • Enable GitHub Actions on [beta] branch
    • Beta Part 1: Part of Mega Dynamic Load/Unload support (#1766)
      • Refactor TelemetryPluginChain ready to start supporting load/unload
      • Move TelemetryInitializer to BaseCore
      • add getPlugin (will be used for remove)
      • Address Channel flush issue
    • Additional Performance enhancements to use provided functions rather than internal polyfill's (#1758)
    • Beta Part 2: Part of Mega Dynamic Load/Unload support (#1768)
      • Add Event Namespace support
      • Minification of constant values
      • Add part of the unload functionality (required for unified teardown() functionality)
    • Beta Part 3: Part of Mega Dynamic Load/Unload support (#1780)
      • Add Core SDK Unload support
    • Fix telemetry chain for null and undefined
    • Beta Part 4: Part of Mega Dynamic Load/Unload support (#1781)
      • Fix function typing issues
      • Update Analytics Extension to start supporting teardown / unload (more tests required)
      • Adds namespace option to instrumentation hooks (for debugging teardown issues)
      • Update AITest Class to log and optionally assert events and hooks that have not been removed
      • Add Update callback when plugins are added / removed (will be extended for config updates)
      • Some minor minification improvements
    • Add missing enum definition
    • Update Sender tests
    • Beta Part 5: Part of Mega Dynamic Load/Unload support (#1782)
      • Add Missing Exports
      • AnalyticsPlugin: Implement teardown and initial test validation
      • Dependencies Plugin: Implement teardown and initial test validation
      • Add flush() to IAppInsightsCore
    • AI Beta: Minor bug fixes and additional debug info (#1787)
    • Lint fixes: Enable Automatic formatting fixes (#1788)
    • Beta Part 6: Part of Mega Dynamic Load/Unload support (#1782) (#1789)
      • Add basic minimal unload / teardown support to all remaining components
      • Update rollup cleanup dependencies
    • Beta: Component Governance Updates to address known dependency issues (#1790)
  • 1793 Master Minification Improvements

  • 1796 Minification - Change to only use const enums internally

  • 1798 More Common Minification Updates

  • 1468 Enable fetch automatic dependency tracking by default

  • 1805 Finalize and Update the processTelemetry helper functions

2.7.4 (Feb 28th, 2022)

  • Updates React Plugin to v3.2.4 (with v2.7.4 as dependency)
  • Updates React Native Plugin to 2.4.4 (with v2.7.4 as dependency)
  • Updates Chrome Debug Extension to 0.2.4

This release is primarily a performance improvement release where we will now use any built in (or provided polyfill) function over the internal polyfills for

  • String trim()
  • String endsWith()
  • String startsWith()
  • Additional Date toISOString()
  • Array isArray()
  • Array indexOf()
  • Array map()
  • Array reduce()
  • Object freeze()
  • Object seal()

Changelog

  • 1754 update react plugin readme

  • 1758 Additional Performance enhancements to use provided functions rather than internal polyfill's

2.7.3 (Jan 31st, 2022)

  • Updates the @microsoft/applicationinsights-shims module to 2.0.1
  • Updates React Plugin to v3.2.3 (with v2.7.3 as dependency)
  • Updates React Native Plugin to 2.4.3 (with v2.7.3 as dependency)
  • Updates Chrome Debug Extension to 0.2.3

Changelog

  • 1735 [BUG] Dependency tracking is disabled when using an Embedded IE browser control

  • 1736 [BUG] New Fetch keepAlive support can cause duplicate events to be sent during unload processing

  • 1745 [Documentation] Document the deployed Module formats and release process

  • 1746 [Documentation] Update AISku Size tracking

  • 1744 Address CodeQL issues from https://github.com/microsoft/ApplicationInights-JS/security/code-scanning

  • Update to Rush 5.61.3 and NPM 8.4.0
  • 1750 [Performance] Use the Date.toISOString() native function if it exists

  • 1753 [Performance] Cache the result of the getGlobal() to reduce the number of typeof expressions

2.7.2 (Dec 7th, 2021)

Changelog

  • 1729 [BUG] Addition of stdDev metric support has broken custom metric reporting from #1680

  • 1727 [BUG] Cannot track exception from service worker

  • 1731 Component Governance - Upgrade to npm v8.1.4

2.7.1 (Nov 4th, 2021)

Changelog

  • 1667 Allow properly disposing AI

    • expose internal log poller #1674
  • 1683 Add support to optionally configure the events used for detecting and handling when page unload and flushing occurs

  • 1655 [BUG] When using Multiple instances of AI only the first instance is correctly reporting ajax events

  • 1093 "Pause" sending of messages

  • 1692 [BUG] Field 'ai.operation.name' on type 'ContextTagKeys' is too long. Expected: 1024 characters"

  • 1691 [BUG] Multiple errors are getting thrown and swallowed during initialization when no instrumentation Key is provided

    • DiagnosticLogger: Fix typo in defining the console function #1699
  • 1676 React Plugin trackTrace method

    • add trackTrace and expose analytics extension to react plugin #1697
  • 1680 [BUG] trackMetric does not track stdDev nor sum #1701

  • fix readme traceID generate method #1687
  • Update package.json to include the repository #1696
  • Governance Updates -- update used dependencies #1694
  • Refactor publishing script to combine shared content and support separate nightly container. #1677
  • Enable EsLint auto fixing rules for extra-semicolons, dangling commas and tailing spaces #1669
  • Update Perf Mark and Measure documentation and some exports #1666
  • Update Release script to provide better automated creation of nightly builds #1664

2.7.0 (Sept 7th, 2021)

Major change: Upgrades build environment to TypeScript 4.x

  • No known breaking, configuration or definition changes

Changelog

  • 1640 [BUG] enableAjaxErrorStatusText: false (which is the default setting) does not turn off logging error response body

  • 1642 trackEvent() doesn't allow replacing the iKey

  • 1647 [BUG] customProperties parameter missing from trackException function

  • 1648 Update error reporting when a plugin throws an exception

  • 1650 [DebugPlugin] Add an option to disable DebugPlugin processTelemetry logging

  • 1653 Some requests are returning a CORB error for responses containing text content type

    • The warning is only being reported via the sendBeacon request, therefore not loss of events
    • Changes the 'unload' operations to try and use fetch with keepalive if available, fallsback to sendBeacon()
    • Also attempts to send as manay events as possible via sendBeacon, when the payload size is > 64kb
  • 1656 [BUG] 'Cannot use 'in' operator to search for 'ver' in Timeout', name: 'TypeError'}​​​​​

  • 1660 [BUG] ITelemetryTrace parentId cannot be set to undefined

Includes: 2.7.0-beta.1 Milestone

  • 1171 Update to TypeScript 4.x

  • 1526 [TypeScript Compile Error] Property 'sessionManager' does not exist on type 'ITelemetryContext'

    • 1627 Add sesId to allow access to sessionManager session info

  • 1471 Convert undefined to blank in customDimensions?

    • 1630 Convert undefined custom properties to empty string

  • 1585 ai_user cookie not present after re-enabling the cookie

  • 1561 How to enrich dependencies logs with context at the beginning of api call?

    • 1624 Provide a way to enrich dependencies logs with context at the beginning of api call

  • 1633 Add GitHub Automated Lock closed issue action

New feature (may be release after primary release - out of band)

  • 617 Add performance.mark and performance.measure for performance browser tool integration

2.7.0-beta.1 (August 24th, 2021)

  • 1171 Update to TypeScript 4.x

  • 1526 [TypeScript Compile Error] Property 'sessionManager' does not exist on type 'ITelemetryContext'

    • 1627 Add sesId to allow access to sessionManager session info

  • 1471 Convert undefined to blank in customDimensions?

    • 1630 Convert undefined custom properties to empty string

  • 1585 ai_user cookie not present after reenabling the cookie

  • 1561 How to enrich dependencies logs with context at the beginning of api call?

    • 1624 Provide a way to enrich dependencies logs with context at the beginning of api call

  • 1633 Add GitHub Automated Lock closed issue action

Update React plugin to v3.2.0-beta.1

  • Update Core dependency to v2.7.0-beta.1 Core changes

Update React Native plugin to v2.4.0-beta.1

  • Update Core dependency to v2.7.0-beta.1 Core changes

2.6.5 (August 3rd, 2021)

2.6.5 Milestone

Changelog

  • 1608 [BUG] empty messages for unhandled promise rejections

  • 1610 [BUG] error logging an error--need to null-check reason

  • 1621 [Task] Create and publish Sub Resource Integrity (SRI) hashes for the generated scripts

  • 1607 Remove AngularPlugin code from master and direct to new repo and angularplugin-legacy branch

  • 1606 Split Tests into Unit / Perf and update all active tests to use common test project

  • 1613 Update Dependencies

  • 1617 Add Stale Issue / PR GitHub Action

Update React plugin to v3.1.5

  • Update Core dependency to ^2.6.5 Core changes

Update React Native plugin to v2.3.5

  • Update Core dependency to ^2.6.5 Core changes

2.6.4 (July 6th, 2021)

2.6.4 Milestone

Changelog

  • 1567 [BUG] Unit of "PageVisitTime" is well hidden

  • 1579 Add 307 Redirect Response

  • 1580 [BUG] URL without host fails in CanIncludeCorrelationHeader

  • 1586 [BUG] namePrefix is not getting assigned to ai_user Cookie

    • 1587 ai_user cookie should use userCookiePostfix for user cookie storage

  • 1590 Task 9901543: Remediate security vulnerabilities (Build Dependencies)

  • 1596 Apply the eslint fixes (from Component Governance policy Checks)

  • 1597 [BUG] The Pointer Events for the DebugPlugin are getting blocked

  • 1599 Add visibilitychange event to the set of events tracked for triggering page unload

  • 1602 [BUG] DebugPlugin - helpers.js:334 Uncaught TypeError: Cannot convert a Symbol value to a string

  • 1472 [Enhancement] Add config to exclude a specific request auto tracking

  • 1446 [FEATURE REQUEST] Ability to stop requests being tracked for array of domains

Update React plugin to v3.1.4

  • Update Core dependency to ^2.6.4 Core changes

Update React Native plugin to v2.3.4

  • Update Core dependency to ^2.6.4 Core changes

2.6.3 (June 8th, 2021)

2.6.3 Milestone

Changelog

  • 1268 Investigate and add a sender that uses fetch when XMLHttpRequest is not available

  • 1545 Cannot modify the request headers and cookies when using a custom endpoint

  • 1546 [Typings] Update the TypeScript typings to identify the readonly properties/fields and dynamic values of the snippet

  • 1541 ITelemetryContext.user is sometimes null - setAuthenticatedUserContext throws

  • 1569 [BUG] Authorization header included when enableRequestHeaderTracking is enabled

    • As part of this change the ["Authorization", "X-API-Key", "WWW-Authenticate"] headers will NO longer be logged when enableRequestHeaderTracking is enabled, if you want these headers to be sent to AzureMonitor you will need to override the default ignoreHeaders config which excludes them (See the Configuration settings).
  • 1558 [BUG] Durations reported as zero (00:00:00.000) in Angular SPA for router changes

  • 363 Script error: Browser exception message not providing information type and method

  • 1568 Add VSCode specific exclusions

  • 1572 Task 9901543: Remediate security vulnerabilities

Update React plugin to v3.1.3

  • Update Core dependency to ^2.6.3 Core changes
  • Update DynamicProto version 1.1.4 (Removes unnecessary dependencies)

Update React Native plugin to v2.3.3

  • Update to React-Native 0.64.2
  • Update Core dependency to ^2.6.3 Core changes
  • Update DynamicProto version 1.1.4 (Removes unnecessary dependencies)

2.6.2 (April 22nd, 2021)

2.6.2 Milestone

Changelog

  • 1536 Update DynamicProto version 1.1.2 (Fixes IE7 mode issue originally reported in #1534)

  • 1280 Investigate removing the globals __extends() and __assign() populated by applicationinsights-shims

  • 1523 Remove exposing global instances of __extends() and __assign() and update sideEffects usage (by removing globals)

  • 1538 [BUG] Telemetry Buffer Getting Cleared in Offline Mode - Online Status Incorrectly Initialized in Offline Listener

  • 1528 [BUG] correlationHeaderExcludePatterns is not honored in Ajax calls

  • 1516 [BUG] App insight library will flush telemetry using beforeUnload event but this event is cancellable

  • 1509 [BUG] Investigate changing the sideEffects: false to list only the files that include the shims module from the all AI modules so that webpack can evaluate correctly

  • 1517 [BUG] addHousekeepingBeforeUnload should also be listening to the 'unload' event

  • 1524 [BUG] Config items are not functional for current snippet disableFlushOnBeforeUnload, disableFlushOnBeforeUnload and maybe others

  • 1440 [BUG] PageViewPerformanceManager.populatePageViewPerformanceEvent() is always returning zero for the network time

  • 1393 [BUG] enableAutoRouteTracking should also update the Operation Name with the hashroute

  • [BUG] Add test coverage for #1518
  • 1510 Update PageView operation name to include the hash

  • 1522 add click plugin version to sdkversion tag

  • 1535 add click plugin js to cdn

Update React plugin to v3.1.1 (April 26th, 2021)

  • Update Core dependency to ^2.6.2 Core changes
  • Update Shims dependency to ^2.0.0 (to address the __extends() and __assign()) issue
  • 1536 Update DynamicProto version 1.1.2 (Fixes IE7 mode issue originally reported in #1534)

Update React Native plugin to v2.3.1

  • Update Core dependency to ^2.6.2 Core changes
  • Update Shims dependency to ^2.0.0 (to address the __extends() and __assign()) issue
  • 1536 Update DynamicProto version 1.1.2 (Fixes IE7 mode issue originally reported in #1534)

2.6.1 (Hotfix - March 30th, 2021)

2.6.1 (Hotfix) Milestone

Changelog

  • 1518 P1 - [BUG] v2.6.0 is not re-hydrating the automatic session id correctly for each request

  • 1512 Expose the getCookieMgr() on the snippet proxy and analytics web instances

2.6.0 (March 23rd, 2021)

2.6.0 Milestone

Version bump is due to the following major changes

A large amount of Tree-Shaking improvements have been included in this version, please see the recommendations you may need to apply to your code to take complete advantage of these changes to reduce the overall module sizes (when using NPM packages)

Also includes major changes to the cookie management, please see the readme cookie configuration section and cookie handling changes.

Changelog

  • General Performance improvements / optimizations
  • 1059 Enable W3C distributed tracing on by default with backward compatibility

  • 1076 Multiple Treeshaking enhancements, see recommendations

  • 1091 Enable cookie support after the SDK has been initialized

  • 1125 Disable Cookies

  • 1276 [BUG] Does not work with Closure Compiler (possible fix, now generates applicationinsights-web.d.ts (This version is namespaced) and applicationinsights-web.rollup.d.ts in the dist folder

  • 1434 Ability to specify cookie Path so that AI works behind App Gateway

  • 1473 [BUG] New dts gneration doesn't work when the environment doesn't have powershell (introduced for #1276)

  • 1474 Add initial stamp endpoint redirection logic

  • 1478 [Bug] Ajax tracking for XHR and fetch is not always setting the start time correctly

  • 1496 [BUG] applicationinsights-web npm package does not have types or a types folder.

  • 1498 [BUG][ES6] TypeError: xxx is not a function or TypeError: DynamicProto [XXXX] is not in class heirarchy of [Object] #28

  • 1503 [BUG] New Perf tests are randomly failing when the build environment is busy (tests added as part of #1076 and #1091)

  • Some documentation updates

Update React plugin to v3.1.0

  • Update Core dependency to ^2.6.0 Core changes
  • 1470 Update applicationinsights-react-js to react 17

Update React Native plugin to v2.3.0

  • Update Core dependency to ^2.6.0 Core changes

2.5.11 (January 15th, 2021)

2.5.11 Milestone

Changelog

  • 1452 [BUG] v2.5.10 Snippet Initialization fails to redirect proxied functions -- causing terminal exception

  • 1433 Typo in 'disableInstrumentaionKeyValidation' config property.

Update Click Analytics plugin to v2.5.11

  • Update Core dependency to ^2.5.11 Core changes
  • 1441 [BUG] Fix issues based on pageName,clickevent name and improved the way we collect useful telemetry data

  • Updated Docs

2.5.10 (November 16th, 2020)

2.5.10 Milestone

New extension @microsoft/applicationinsights-clickanalytics-js

Provides the ability to gather telemetry in Web pages to automatic track clicks using data meta tags.

Changelog

  • 1420 Fix issues with for..in usage with prototype extension libraries like ember.js and prototype.js

  • 1417 Adding nuspec for new Snippet nuget package

  • 1415 Update Publishing scripts to allow different container names -- replaces the cdn switch #1415

  • 1411 [BUG] - License file link is invalid #1411

  • 1410 Remove mention of resolution in Device Information

  • 1408 Update publish scripts to support a sub-container

  • 1409 Initial release of new Click Analytics Plugin

  • 1407 Adding logger during core constructor

  • 1403 [Feature Request] Snippet - Add an easier way to inject queue items as part of the snippet config (version 5 of snippet)

  • 1402 [BUG] "ReferenceError: method is not defined" from 2.5.5+

  • 420 CDN endpoint

Update React plugin to v3.0.5

  • Update Core dependency to ^2.5.10 Core changes

Update React Native plugin to v2.2.9

  • Update Core dependency to ^2.5.10 Core changes

2.5.9 (October 5th, 2020)

2.5.9 Milestone

Changelog

  • 1395 Update publishing scripts to support automation

  • 1391 Increase the randomness and size of the sessionId (newId())

  • 1390 using older version of types/cheerio dependecy

  • 1389 take out SPO support

  • 1388 Bump shims version for React, React-Native and Angular to latest.

  • 1384 Add sideEffects field to applicationinsights-shims package.json

    • Use updated Shims module (v1.0.2)
  • 1381 [BUG] NPM package for @microsoft/applicationinsights-angularplugin-js does not have a dist folder

  • 1377 [BUG] Session storage buffers being initialized though configured not to use

  • 1375 Make AI JS SDK for with NativeScript-Angular

    • Use updated Shims module (v1.0.1)
  • 1374 indexof is wrongly cased

  • 1365 correlationHeaderExcludePatterns added to IConfig

  • 1364 [BUG] PerfManager and NotificationManager are not exported in AISKU

  • 1363 [BUG] correlationHeaderExcludePatterns missing from types

  • 1361 Debug plugin readme changes

  • 1359 Add trackMetric method for Angular plugin

  • 1358 Add snippet setup for SPO extension solution and update README

New Package applicationinsights-shims v1.0.2

  • 1384 Add sideEffects field to applicationinsights-shims package.json

New Package applicationinsights-shims v1.0.1

  • 1375 Make AI JS SDK for with NativeScript-Angular

Update React plugin to v3.0.4

  • Update Core dependency to ^2.5.9 Core changes

Update React Native plugin to v2.2.8

  • Update Core dependency to ^2.5.9 Core changes

2.5.8 (August 31st, 2020)

2.5.8 Milestone

Changelog

  • 1356 add documentation on how to make snippet changes

  • 1355 update angular package name

  • 1350 [BUG] The new IPerfEvent is using Date.now() which is not supported in an ES3 environment

  • 1349 Update angular plugin track pageview logic and test

  • 1343 [BUG] IPerfManager interface - the create() function is defined to return an IPerfEvent and not an IPerfEvent?

  • 1340 Instrumentation Key validation

  • 1018 Error Mismatched anonymous define() module

    • 1352 add .cjs.js and .cjs.min.js

Update applicationinsights-rollup-es3 to v1.1.3

  • 1350 [BUG] The new IPerfEvent is using Date.now() which is not supported in an ES3 environment

    • Added additional checks for Date.now() and Performance Api perf.now()

Update React plugin to v3.0.3

  • Update Core dependency to ^2.5.8 Core changes

Update React Native plugin to v2.2.7

  • Update Core dependency to ^2.5.8 Core changes

2.5.7 (August 7th, 2020)

2.5.7 Milestone

Changelog

  • 1335 Add Performance / Testing support

  • 1334 [BUG] Getting XMLHttpRequest and XDomainRequest is not defined errors for gatsby environment

  • 1333 [BUG] DebugPlugin various updates

  • 1331 AppInsightsCore: Enable setting NotificationManager during initialization

    • 1076 Refactor code to provide better tree shaking and minification of generated code

    • Updated Sender and support classes to move all private properties and methods into constructor closure
  • 1328 applicationinsights-debugplugin-js: fixed various issues and updating to beta-2

  • 1323 Add Retry as a SendRequestReason

  • 1324[BUG] Type 'ReactNativePlugin' is not assignable to type 'ITelemetryPlugin'

    • Refactored the Plugin to extend BaseTelemetryPlugin (part of the #1076 work)
  • 1321 [BUG] @microsoft/applicationinsights-web fails to initialize with latest version

  • 1319 fix incorrect references to configuration parameter names

  • 1316 Update dependency version of DynamicProto

    • Move all private properties and methods into constructor closure
    • 1316 Update dependency version of DynamicProto

Updated React plugin to v3.0.2

  • Update Core dependency to ^2.5.7 Core changes
  • 1335 Add Performance / Testing support

Updated React Native plugin to v2.2.6

  • Update Core dependency to ^2.5.7 Core changes
  • 1335 Add Performance / Testing support

  • 1324 [BUG] Type 'ReactNativePlugin' is not assignable to type 'ITelemetryPlugin'

    • Refactored the Plugin to extend BaseTelemetryPlugin (part of the #1076 work)
  • 1076 Refactor code to provide better tree shaking and minification of generated code

    • Move all private properties and methods into constructor closure
    • 1316 Update dependency version of DynamicProto

2.5.6 (Jul 6th, 2020)

2.5.6 Milestone

New (Beta) extension applicationinsights-debugplugin-js

  • Created the initial extension to help developers understand, track, visualize and fix issues with events
  • This extension injects a UI onto your page details for the component is available at https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/applicationinsights-debugplugin-js
  • This is a beta release so the UI, config etc are not yet complete, feedback for features, suggestions or changes are welcome -- please create an Issue
  • The detailed view is still under construction and contains known bugs, these will be address in the next few months (releases) as we build out the module. We had not originally planed to have any detailed view as part of this initial beta release.

Changelog

  • 1311 Allow the generated modules to extend the namespace defined by "name" in rollup config -- rather than always replace.

    • Changes the way the "Microsoft.ApplicationInsights" is defined for each module to all modules to be added to the same namespace
  • 1309 When using prototype js the SessionStorage become corrupted causing requests internal exceptions

  • 1303 Task 7027291: Investigate CDN Configuration to support custom domain (automate CDN deployment scripts)

  • 1299 Releasing core queue as soon as possible (fixes lost events from page load immediate unload with no additional events)

  • 1297 Created initial applicationinsights-debugplugin-js

  • 1289 [Documentation] doc: SPO set up instruction

  • 1286 [Documentation] Update JS SDK Snippet documentation with bug fixes (new v4 snippet)

  • 1283 [BUG] (Snippet v3) AppInsights stub methods captured incorrect method names in the closure

  • 1262 [BUG] Custom properties added with addTelemetryInitializer are ignored for exceptions

  • 1245 React Native - AI (Internal): 19 message: "Could not add handler for beforeunload and pagehide"

    • Add isReactNative() function for detecting the runtime environment
  • 1095 Add an Error Boundary to the React plugin

  • 1089 Blocking certain URIs/Patterns from fetch tracking (patch included)

    • Added new config 'correlationHeaderExcludePatterns' to allow disabling correlation headers using regular expressions

Updated React plugin to v3.0.1

  • 1311 Allow the generated modules to extend the namespace defined by "name" in rollup config -- rather than always replace.

    • Changes the way the "Microsoft.ApplicationInsights" is defined for each module to all modules to be added to the same namespace

Update applicationinsights-rollup-es3 to v1.1.2

  • 1311 Allow the generated modules to extend the namespace defined by "name" in rollup config -- rather than always replace.

2.5.5 (Jun 2nd, 2020)

2.5.5 Milestone

Updated React plugin to v3.0.0

  • Updated to TypeScript 3.x
  • Removed React plugin from main rush pipeline
  • 991 Don't work with React HOOKS

    • 1120 Introducing React Hooks for AppInsights #1120

New Package applicationinsights-shims v1.0.0

  • Created to remove dependency on TSLib as v 1.13.0 has introduced build breaks
    • provides internal implementation of __extends() and __assign() when no pre-existing version is present

Changelog

  • 1278 Add optional 'eventsSendRequest' notification to NotificationManager

  • 1269 TsLib v1.13.0 has breaking change (Remove dependency on TSLib)

  • Removed React plugin from main rush pipeline
  • 991 Don't work with React HOOKS

    • 1120 Introducing React Hooks for AppInsights #1120

  • 1274 Fix for withAITracking wrapping functional components.

  • Using crypto to generate GUIDs when available (Make GUID more random)
  • 1260 [BUG] Can't include Correlation Header on IE can fail

  • 1258 Update snippet to support reporting script load failures

  • 1251 [BUG] ajax.ts is using string trim() which is not supported on IE7/8

  • 1249 Identify whether the script is being consumed via the CDN or NPM package

  • Several minor documentation updates

2.5.4 (Apr 7th, 2020)

2.5.4 Milestone

Changelog

  • 1242 Upgrading the tslib dependency to 1.11.1

  • 1233 [BUG] Duplicate React dependency

  • 1232 [BUG] window.appInsights.properties is marked private

    • Fix issue by always exposing window.appInsights.context
  • 1240 [BUG] Telemetry correlation headers are not included for all fetch requests

  • 1229 [BUG] Unable to include telemetry correlation headers

  • 1227 SPFX - undefinedundefined is not defined

  • 1221 npm @microsoft/applicationinsights-web: license information missing in package.json

  • 1191 [BUG] ICustomProperties does not support setting values

2.5.3 (Mar 25th, 2020)

2.5.3 Milestone

Changelog

  • 1224 [BUG] When running in IE7/8 the app insights doesn't initialize and gets stuck in a loop (long running script)

2.5.2 (Mar 11th, 2020)

Changelog

  • 1217 [BUG] App Insights fails when the XHR object is not extensible (or frozen)

  • 1186 [BUG] App Insights initialization setting 'enableAjaxErrorStatusText is not working #1218

2.5.1 (Mar 9th, 2020)

Changelog

  • 1210 [BUG] Typescript error when using @microsoft/applicationinsights-web 2.5.0 and "noImplicitAny"/"strict" option

  • 1207 [BUG] The latest version 2.4.4 cannot connect front-end with back-end on the Application Map on Application Insights

2.5.0 (Mar 9th, 2020)

Changelog

  • 1204 When a fetch polyfill is installed there reporting endpoint is also causing events to be sent

  • 1202 ai_user and ai_session cookies not set #1203

  • 1201 add to auto track exceptions in react native plugin

  • 1199 Build is breaking when you do a "rush update --full --purge --recheck" due to tslib v1.11.0 update

  • 1194 XHR/Fetch enhancement - add additional telemetry from window.performance #1195

  • 1193 add sanitizer for operationName

  • 1189 Add the option to specify the refUri with stopTrackPage #1190

  • 1186 App Insights initialization setting 'enableAjaxErrorStatusText' is not working #1187

XHR/Fetch enhancement

Adds additional performance data derived from the window.performance.getEntries() for the fetch or XHR request.

Configuration options | Name | Default | Description | |------|---------|-------------| | enableAjaxPerfTracking | false | Default false. Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics. | maxAjaxPerfLookupAttempts | 3 | Defaults to 3. The maximum number of times to look for the window.performance timings (if available), this is required as not all browsers populate the window.performance before reporting the end of the XHR request and for fetch requests this is added after its complete. | ajaxPerfLookupDelay | 25 | Defaults to 25ms. The amount of time to wait before re-attempting to find the windows.performance timings for an ajax request, time is in milliseconds and is passed directly to setTimeout().

Auto track exception React Native Plugin

This has been enabled by default in the updated version. It can be disabled by adding the disableExceptionCollection config value with a value of true.

2.4.4 (Feb 5th, 2020)

Changelog

  • 1182 Fix error TS2430: Interface 'Window' incorrectly extends interface 'WindowEventHandlers'

  • 1185 Rollback namespace overwrite change

2.4.3

Changelog

  • Syntax error tools/rollup-es3/src/es3/Es3Tokens.ts #1179

2.4.2

ES3 Support

An additional conversion was required for ES3 support as TypeScript was adding a getter for embedding a constant enum into the Common class.

Changelog

  • 1177 Add additional checks and polyfil for TypeScript get translations for constants

v 2.4.1...2.4.0

ES3 Support

With this release the source files can be loaded in an ES3 environment (IE7/8) and send requests to the server. As part of this change you will now receive requests from users using an older browser, prior to this version users using an ES3 base browser will (most likely) have been getting a javascript error, which would have caused no data to be sent.

Enable support for reusing plugins in multiple instances of AppInsights #1132

We have added upport to enable reusing the same plugin in different instances of AppInsights, owned by the same application (but using different Instrumentation keys) is required so that they can reuse a single Plugin instance for all instances.

This changes introduces a new IProcessTelemetryContext interface that is passed to the processTelemetry() method so that the plugins can use the current request context for the event rather than the context during initialization.

To assist with creating plugins we have also introduced a base class that you can use for creating new plugins BaseTelemetryPlugin, details are included on the Readme

Changelog

  • 1175 [BUG] Typescript build with 2.4.0 breaks #1173

  • 1174 Legacy Manage SameSite Cookie Settings #1126

  • 1172 Update SameSite logic to handle UserAgents that don't support the attribute

  • 1169 Fixup Rollup ES3 plugin package.json

  • 1167 Add better support for referencing global objects from a window and web workers

  • 1164 add null check for sessionManager

  • 1162 [BUG]AppInsights not working in IE7 #1142

  • 1161 include response error data

  • 1159 Export Common Telemetry classes in Snippet

  • 1157 fix: only change SameSite when secure

  • 1154 Queue events when track is called and not all extensions are initialized

  • 1153 Do not clean telemetryInitializers during initialization

  • 1150 Remove interface code from API reference and link

  • 1135 fix: dont block corr on empty location host

  • 1133 Enable support for reusing plugins in multiple instances of AppInsights #1132

  • 1129 fix: console logging not honoring setting

  • 1122 fix anchor link

  • 1116 Move tslib to sku dependencies

  • 1113 [Enhancement] AI is not catching all "Unload" dom events #1080

v 2.3.1

Changelog

  • 1102 Enable support for IE8

  • 1096 Add extra window nullchecks for non-browser environments

  • 1105 Fix issue where operation name is overwritten

v 2.3.0...2.2.4

Changelog

  • 1066 Adds Connection String support

  • 1061, #1065,#1067, #1088 misc bug fixes

v 2.2.4

Changelog

  • 1054 Fix issue with AppInsightsCore refactor

v 2.2.3

Changelog

  • 1051 Add to call track trace on user init sending browser info to the end point when loggingLevelTelemetry config is on

  • 1050 Address issue https://github.com/MicrosoftDocs/azure-docs/issues/39011

  • 1049 Fix issue with PageViewPerformance event being sent with undefined name property

  • 1041 Add tslint error screening

  • 1038 Re-organize repo folders

  • 1035 Update to use PerformanceNavigationInterface for supported browsers

v 2.2.2

Changelog

  • 1030 Fix issue with appId correlation being appended with an incorrect format

v 2.2.1

Changelog

  • 1015 Update to use beaconSender for page unload when browser supports Beacon API

  • 1028 Fix issue where window.location is not defined

  • 1021 Fix issue with not parsing correlationContext

  • 1020 Disable by default logging to console internal SDK errors. Enable by default logging as telemetry for internal SDK errors

v 2.2.0

Changelog

  • 946 Feature: Adds automatic incoming/outgoing header tracking. Outgoing header tracking is experimental and may be miss some headers

  • 973 Feature: Support propagation of W3C compatible distributed tracing headers

  • 983: Fix issue regarding incorrect referrer uri when using enableAutoRouteTracking

  • 984: Fix issue where adding custom properties/tags would not work in telemetry processors

  • 999: Fix IE issue when using enableAutoRouteTracking

  • 1000

v 2.1.1

Patch release containing fixes to automatic Single Page Application route change tracking via enableAutoRouteTracking

Changelog

970 - Fixes #967 #969

v 2.1.0

Highlights

Source Map Support

*You do not need to upgrade for drag and drop to work. It will work on all previous and future versions of the javascript (and Node.js) SDK

https://i.imgur.com/Efue9nU.gif You can now drag and drop your source maps onto your Exception Telemetry in the Azure Portal to unminify your callstack. Please open an issue or use the Feedback button in the Portal if a source map you've uploaded is not working as intended. This is a first iteration and in a future update, your source maps will be automatically unminified.

SPA Route Change Tracking

You can set enableAutoRouteTracking: true to enable state based route tracking for your Single Page Application (React, Angular, Vue, etc). You do not need to install a separate plugin to use this configuration option.

This setting will cause a new Page View telemetry item to be sent each time your app's route changes (including Hash route changes).

Changelog

  • 920 Resolve jest testing issues when using React plugin

  • 928 Make analytics plugin have last priority

  • 936 Fallback to XHR Sender when beacon sender tries to send >64 KB

  • 947 Add SPA route change tracking

  • 948 Docs: Source map support

  • 952 Re-enable samplingPercentage functionality

  • 918, #919, #932 #933 #935 #939 #940 #951

v 2.0.1

trackException Change

This update has a couple of non-breaking API changes. Namely, trackException is now consistent with the Node.js SDK. The only change here is the named argument is renamed from error to exception. A shim is in place so any existing usages of trackException will still work, and the old field is marked as optional, so any type-checked files will still "compile". There are no breaking changes with this change, but you are encouraged to use exception as your named argument field as error will be deprecated in a future major version.

Old

appInsights.trackException({ error: new Error() });

New

appInsights.trackException({ exception: new Error() });

Correlation Header Domain Whitelisting #869

Second, the ability to only send correlation headers to specific, whitelisted domains is now available as a configuration option , correlationHeaderDomains. It accepts an array of domain strings. Wildcards ("") are okay. By populating this array, all other domains which your application makes requests to will *not** have correlation headers included. This setting makes it easy to avoid OPTIONS requests to services outside of your control.

You can use the inclusion list and the exclusion list in conjunction with each other to add correlation headers to a particular domain, example.com, and at the same time exclude headers from a prefixed version of it, no-headers.example.com.

Tag Override Change #903

Performing custom tag overrides is now more consistent with all of the other Application Insights SDKs, in that it is modified via a simple key-value dictionary. There are no breaking changes with this update, and if you are setting any tags via the old way, they will still work as they do now. You are encouraged to update them since the old way will be deprecated in a future major version release.

Old

var telemetryInitializer = (item) => {
  item.tags.push({ "ai.cloud.role": "My Web App" });
};
appInsights.addTelemetryInitializer(telemetryInitializer);

New

var telemetryInitializer = (item) => {
  item.tags["ai.cloud.role"] = "My Web App";
};
appInsights.addTelemetryInitializer(telemetryInitializer);

Changelog

869 - config: add ability to whitelist specific domains for adding correlation headers

893 - docs: fix sample configuration settings

899 - common: replace Array.some with Array.forEach to simplify polyfill story, add tests

902 - snippet: add missing methods to lazy loaders

903 - tags can now be set with same API as other AI SDKs

904 - rename IExceptionTelemetry.error --> IExceptionTelemetry.exception

905 - react: fix plugin causing jest tests to fail

907 - docs: add mention of how to update current context's operation

908 - react: remove analytics package dependency

910 - docs: update context refresh information

913 - Remove code from adding libVer from extensions

918 - automatically add ai.operation.name tag, add id to pageview telemetry

919 - fix issue with namePrefix not affecting send buffers

v 2.0.0

Changelog

  • 878 Fix issue with missing pageviewperformance

  • 881 Change access level of some non-exposed methods

  • 883 Allow id to be set in Exception telemetry