Application Insights JavaScript SDK

To avoid any global OUTAGE you MUST change ALL of your CDN usage from https://az416426.vo.msecnd.net/scripts/... to our primary CDN endpoint https://js.monitor.azure.com/scripts/....
See/follow Issue #2457 for updated details
We are currently investigating the available options on how we can avoid / migrate / mitigate this situation, but at this point it is HIGHLY likely that there will be either a temporary or permanent outage of this domain. As we currently have no known way to “migrate” this domain to a different CDN.
Before Getting Started
This SDK is intended for browser environments and is not suitable for other environments, like 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. Will only receive critical bug fixes when no workaround exists — no new features or back-porting from later versions. 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 [email protected] has moved here. If you are looking to upgrade to the new version of the SDK, please see the Upgrade Guide. |
:bulb: Note
When multiple instances of Application Insights with different major version are active within a single session, errors may arise. For further details, please refer to the version conflict doc.
Getting Started
- Create an Application Insights resource in Azure by following these instructions.
- 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.
- 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'
} });
appInsights.loadAppInsights();
appInsights.trackPageView();
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 8, the version is identified by the “sv:” in the script.
<script type="text/javascript">
!(function (cfg){var k,x,D,E,L,C,b,U,O,A,e,t="track",n="TrackPage",i="TrackEvent",I=[t+"Event",t+"Exception",t+"PageView",t+"PageViewPerformance","addTelemetryInitializer",t+"Trace",t+"DependencyData",t+"Metric","start"+n,"stop"+n,"start"+i,"stop"+i,"setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"];function a(){cfg.onInit&&cfg.onInit(e)}k=window,x=document,D=k.location,E="script",L="ingestionendpoint",C="disableExceptionTracking",b="crossOrigin",U="POST",O=cfg.pn||"aiPolicy",t="appInsightsSDK",A=cfg.name||"appInsights",(cfg.name||k[t])&&(k[t]=A),e=k[A]||function(u){var n=u.url||cfg.src,s=!1,p=!1,l={initialize:!0,queue:[],sv:"10",config:u,version:2,extensions:void 0};function d(e){var t,n,i,a,r,o,c,s;!0!==cfg.dle&&(o=(t=function(){var e,t={},n=u.connectionString;if("string"==typeof n&&n)for(var i=n.split(";"),a=0;a<i.length;a++){var r=i[a].split("=");2===r.length&&(t[r[0].toLowerCase()]=r[1])}return t[L]||(e=(n=t.endpointsuffix)?t.location:null,t[L]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||u.instrumentationKey||"",t=(t=(t=t[L])&&"/"===t.slice(-1)?t.slice(0,-1):t)?t+"/v2/track":u.endpointUrl,t=u.userOverrideEndpointUrl||t,(n=[]).push((i="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=e,c=t,(s=(r=f(o,"Exception")).data).baseType="ExceptionData",s.baseData.exceptions=[{typeName:"SDKLoadFailed",message:i.replace(/\./g,"-"),hasFullStack:!1,stack:i+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(D&&D.pathname||"_unknown_")+"\nEndpoint: "+c,parsedStack:[]}],r)),n.push((s=e,i=t,(c=(a=f(o,"Message")).data).baseType="MessageData",(r=c.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+s+")").replace(/\"/g,"")+'"',r.properties={endpoint:i},a)),e=n,o=t,JSON&&((c=k.fetch)&&!cfg.useXhr?c(o,{method:U,body:JSON.stringify(e),mode:"cors"}):XMLHttpRequest&&((s=new XMLHttpRequest).open(U,o),s.setRequestHeader("Content-type","application/json"),s.send(JSON.stringify(e)))))}function f(e,t){return e=e,t=t,i=l.sv,a=l.version,r=D,(o={})["ai.device."+"id"]="browser",o["ai.device.type"]="Browser",o["ai.operation.name"]=r&&r.pathname||"_unknown_",o["ai.internal.sdkVersion"]="javascript:snippet_"+(i||a),{time:(r=new Date).getUTCFullYear()+"-"+n(1+r.getUTCMonth())+"-"+n(r.getUTCDate())+"T"+n(r.getUTCHours())+":"+n(r.getUTCMinutes())+":"+n(r.getUTCSeconds())+"."+(r.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z",iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:o,data:{baseData:{ver:2}},ver:undefined,seq:"1",aiDataContract:undefined};function n(e){e=""+e;return 1===e.length?"0"+e:e}var i,a,r,o}var i,a,t,r,g=-1,h=0,m=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],o=function(){return c(n,null)};function c(t,r){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~t.indexOf("ai.3")&&(t=t.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<m.length;e++)if(0<t.indexOf(m[e])){g=e;break}var n,o=function(e){var a;l.queue=[],p||(0<=g&&h+1<m.length?(a=(g+h+1)%m.length,i(t.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+m[a]+i})),h+=1):(s=p=!0,d(t)))},c=function(e,t){p||setTimeout(function(){t&&!l.core&&o()},500),s=!1},i=function(e){var n,i=x.createElement(E),e=(cfg.pl?cfg.ttp&&cfg.ttp.createScript?i.src=cfg.ttp.createScriptURL(e):i.src=(null==(n=window.trustedTypes)?void 0:n.createPolicy(O,{createScriptURL:function(e){try{var t=new URL(e);if(t.host&&"js.monitor.azure.com"===t.host)return e;a(e)}catch(n){a(e)}}})).createScriptURL(e):i.src=e,cfg.nt&&i.setAttribute("nonce",cfg.nt),r&&(i.integrity=r),i.setAttribute("data-ai-name",A),cfg[b]);function a(e){d("AI policy blocked URL: "+e)}return!e&&""!==e||"undefined"==i[b]||(i[b]=e),i.onload=c,i.onerror=o,i.onreadystatechange=function(e,t){"loaded"!==i.readyState&&"complete"!==i.readyState||c(0,t)},cfg.ld&&cfg.ld<0?x.getElementsByTagName("head")[0].appendChild(i):setTimeout(function(){x.getElementsByTagName(E)[0].parentNode.appendChild(i)},cfg.ld||0),i};i(t)}cfg.sri&&(i=n.match(/^((http[s]?:\/\/.*\/)\w+(\.\d+){1,5})\.(([\w]+\.){0,2}js)$/))&&6===i.length?(T="".concat(i[1],".integrity.json"),a="@".concat(i[4]),S=window.fetch,t=function(e){if(!e.ext||!e.ext[a]||!e.ext[a].file)throw Error("Error Loading JSON response");var t=e.ext[a].integrity||null;c(n=i[2]+e.ext[a].file,t)},S&&!cfg.useXhr?S(T,{method:"GET",mode:"cors"}).then(function(e){return e.json()["catch"](function(){return{}})}).then(t)["catch"](o):XMLHttpRequest&&((r=new XMLHttpRequest).open("GET",T),r.onready
提示:代码过长已自动截断
For optional OS detection with a supporting full SDK CDN release, see the CDN loader example.
OS detection is not enabled by default.
: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.
-
ConnectionString format should follow “InstrumentationKey=xxxx;…” If the string provided does not meet this format, the sdk load process would fail
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.
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 7) |
| cfg |
object [required] |
The IConfiguration passed to the Application Insights SDK during initialization. |
| cr |
boolean [optional] |
Controls CDN fallback retry behavior. By default (true), if the SDK fails to load from the configured src URL, the snippet automatically attempts to load from multiple supported CDN domains in case one or more of them is temporarily unavailable. Set to false to disable this fallback and only attempt the single configured src URL. |
| sri |
boolean [optional] |
Custom optional value to specify whether to fetch the snippet from an integrity file and perform an integrity check. When this option is used, the integrity file is loaded first, affecting the load order and script execution. Hence the ld option will be ignored. Additionally, if the page navigates away before the integrity file is loaded, some events may be lost. |
| dle |
boolean [optional] |
When set to true, prevents the SDK from reporting load failure telemetry. |
| pl |
boolean [optional] |
Custom optional value to specify whether to enable the Trusted Type policy check on the snippet. |
| pn |
string [optional] |
Custom optional value to specify the name of the Trusted Type policy that would be implemented on the snippet, default is ‘aiPolicy’. |
| ttp |
TrustedTypePolicy [optional] |
Custom optional value to specify the Trusted Type policy that would be applied on the snippet src. |
| nt |
string [optional] |
Custom optional value to specify the nonce attribute value that will be applied to the script tag when it is added to the page. |
Internet Explorer: Automatic Version Fallback
Important: When the SDK Loader (snippet) detects that the page is being loaded by Internet Explorer (via the msie or trident/ user agent strings), it will automatically rewrite the src URL to load the v2.x version of the SDK instead of v3.x. For example, ai.3.gbl.min.js will be changed to ai.2.gbl.min.js.
This means that if your application uses the SDK Loader with a v3.x CDN URL and any of your users visit the page with Internet Explorer, they will receive the 2.x version of the SDK. As a result, any APIs or features that are only available in v3.x or later — including the new OpenTelemetry-based APIs — will not exist on the SDK instance for those users. Your code should account for this by checking for the existence of newer APIs before calling them, or by using only APIs that are available in both v2.x and v3.x.
This fallback does not apply when using the NPM package directly, as NPM installations always load the specific version you have installed.
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.3.gbl.min.js",
crossOrigin: "anonymous",
onInit: function (sdk) {
sdk.addTelemetryInitializer(function (envelope) {
envelope.data.someField = 'This item passed through my telemetry initializer';
});
},
cfg: {
connectionString: "YOUR_CONNECTION_STRING"
}});
</script>
Active Public CDN endpoints
To avoid any global OUTAGE you MUST change ALL of your CDN usage from https://az416426.vo.msecnd.net/scripts/... to our primary CDN endpoint https://js.monitor.azure.com/scripts/....
See/follow Issue #2457 for updated details
We are currently investigating the available options on how we can avoid / migrate / mitigate this situation, but at this point it is HIGHLY likely that there will be either a temporary or permanent outage of this domain. As we currently have no known way to “migrate” this domain to a different CDN.
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.
Due to Issue #2457 we are now declaring that you MUST always use js.monitor.azure.com domain.
| State |
CDN Endpoint |
Description |
| Primary |
https://js.monitor.azure.com/scripts/b/ai.3.gbl.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 DO NOT USE |
~~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. Due to Issue #2457 we are now declaring that you MUST always use js.monitor.azure.com domain. |
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'
} });
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.
<script type="text/javascript" src="/pathToAIJSSDK.js"></script>
After JS script has loaded, include the following snippet to initialize Application Insights:
<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: '|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7'});
appInsights.startTrackPage("pageName");
appInsights.stopTrackPage("pageName", null, {customePropertiesName: "some value"}, {customerMeasurementsName: 144});
appInsights.startTrackEvent("event");
appInsights.stopTrackEvent("event", null, {customePropertiesName: "some value"}, {customerMeasurementsName: 150});
appInsights.flush();
For manually tracked dependencies, see the dependency ID format and W3C correlation notes.
Custom properties can be included in your telemetry through the properties named argument. This can be done with any of the Track APIs except stopTrackPage and stopTrackEvent.
appInsights.trackEvent({
name: 'some event',
properties: {
prop1: 'string',
prop2: 123.45,
prop3: { nested: 'objects are okay too' }
}
});
When using stopTrackPage and stopTrackEvent, you can pass in data categorized by types:
Strings: These should be included under the properties field.
Numbers: Add these under the measurements field.
Remember, the order of the properties and measurements should not be altered. You can achieve this using the following code structure:
appInsights.startTrackEvent("event name");
appInsights.stopTrackEvent("event name", {
stringProp1: 'string',
stringProp2: {nested: "objects are okay too", key: "value"}
},
{numProp1: 3.15, numProp2: 90000}
)
OpenTelemetry Tracing API
The Application Insights JavaScript SDK includes an OpenTelemetry-compatible tracing API that allows you to use familiar OpenTelemetry patterns for distributed tracing while automatically sending telemetry to Azure Application Insights.
Key Features:
- Use OpenTelemetry-like tracing APIs following industry-standard patterns
- Automatic telemetry creation with full distributed tracing support
- Parent-child span relationships for nested operations
- Compatible with OpenTelemetry API specifications (tracing only)
Learn More:
For comprehensive documentation on the OpenTelemetry tracing API, including tracer management, span utilities, helper functions, and detailed examples, see:
Note: This is an OpenTelemetry-compatible tracing API implementation, not a full OpenTelemetry SDK. Only tracing APIs are supported (metrics and logs APIs are not included).
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.
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);
appInsights.trackTrace({message: 'this message will not be 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.
Advanced Setting Using Config/Extensions
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 |
| 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 |
Removed from v3.x, 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. |
| 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. |
| 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 |
string[] |
undefined |
[Optional] An optional value that will be added as name prefix for storage name. |
featureOptIn (#feature) since 3.0.3 |
IFeatureOptIn |
undefined |
[Optional] Set Feature opt in details. |
throttleMgrCfg since 3.0.3 |
{[key: number]: IThrottleMgrConfig} |
undefined |
[Optional] Set throttle mgr configuration by key. |
| 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 3.1.1. |
| disablePageUnloadEvents |
string[] |
undefined |
[Optional] An array of the page unload events that you would like to be ignored. See detailed documentation. Unload events include “beforeunload”, “unload”, “visibilitychange” (with ‘hidden’ state) and “pagehide”. This can be used to avoid jQuery 3.7.1+ deprecation warnings by configuring as disablePageUnloadEvents: ["unload"]. |
| disablePageShowEvents |
string[] |
undefined |
[Optional] An array of page show events that you would like to be ignored. See detailed documentation. Page Show events include “pageshow” and “visibilitychange” (with ‘visible’ state). |
expCfg since 3.3.1 |
IExceptionConfig |
undefined |
Set additional configuration for exceptions, such as more scripts to include in the exception telemetry. |
| redactQueryParams |
string[] |
["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"] |
[Optio |
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论