适用于网页的 Application InsightsApplication Insights for web pages

了解网页或应用的性能和使用情况。Find out about the performance and usage of your web page or app. 如果将 Application Insights 添加到页面脚本,可以获取页面加载和 AJAX 调用的时间、浏览器异常和 AJAX 失败的计数和详细信息,以及用户和会话计数。If you add Application Insights to your page script, you get timings of page loads and AJAX calls, counts, and details of browser exceptions and AJAX failures, as well as users and session counts. 所有这些信息可按页面、客户端 OS 和浏览器版本、地理位置和其他维度细分。All these can be segmented by page, client OS and browser version, geo location, and other dimensions. 可以针对失败计数或页面加载缓慢情况设置警报。You can set alerts on failure counts or slow page loading. 并且通过在 JavaScript 代码中插入跟踪调用,可以跟踪网页应用程序的不同功能的使用情况。And by inserting trace calls in your JavaScript code, you can track how the different features of your web page application are used.

可以在任何网页中使用 Application Insights - 刚刚添加了 JavaScript 的简短片段。Application Insights can be used with any web pages - you just add a short piece of JavaScript. 如果 Web 服务是 JavaASP.NET,则你可以将服务器端 SDK 与客户端 JavaScript SDK 结合使用,以全方面地了解应用的性能。If your web service is Java or ASP.NET, you can use the server-side SDKs in conjunction with the client-side JavaScript SDK to get an end-to-end understanding of your app's performance.

添加 JavaScript SDKAdding the JavaScript SDK

  1. 首先需要一个 Application Insights 资源。First you need an Application Insights resource. 如果你尚未获得资源和检测密钥,请遵照有关创建新资源的说明If you don't already have a resource and instrumentation key, follow the create a new resource instructions.
  2. 从你要将 JavaScript 遥测数据发送到的资源(从步骤 1 中得到的)复制检测密钥(也称为“iKey”)。你需要将该密钥添加到 Application Insights JavaScript SDK 的 instrumentationKey 设置。Copy the instrumentation key (also known as "iKey") for the resource where you want your JavaScript telemetry to be sent (from step 1.) You will add it to the instrumentationKey setting of the Application Insights JavaScript SDK.
  3. 通过以下两个选项之一,将 Application Insights JavaScript SDK 添加到网页或应用:Add the Application Insights JavaScript SDK to your web page or app via one of the following two options:


仅使用一种方法将 JavaScript SDK 添加到应用程序。Only use one method to add the JavaScript SDK to your application. 如果使用 NPM 安装程序,请不要使用代码片段,反之亦然。If you use the NPM Setup, don't use the Snippet and vice versa.


NPM 安装程序会将 JavaScript SDK 作为依赖项安装到项目中,启用 IntelliSense,而代码片段则会在运行时获取 SDK。NPM Setup installs the JavaScript SDK as a dependency to your project, enabling IntelliSense, whereas the Snippet fetches the SDK at runtime. 两者都支持相同的功能。Both support the same features. 但是,需要更多自定义事件和配置的开发人员通常会选择 NPM 安装程序,而需要快速启用现成 Web 分析的用户则选择代码片段。However, developers who desire more custom events and configuration generally opt for NPM Setup whereas users looking for quick enablement of out-of-the-box web analytics opt for the Snippet.

基于 npm 的设置npm based setup

通过 NPM 安装。Install via NPM.

npm i --save @microsoft/applicationinsights-web

注意: Typings 已包含在此包中,因此无需安装单独的 typings 包 。Note: Typings are included with this package, so you do not need to install a separate typings package.

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

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

基于代码片段的设置Snippet based setup

如果应用不使用 npm,则可以通过直接使用 Application Insights 来检测网页:只需将此代码片段粘贴到每个页面的顶部即可。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. 最好是将它用作 <head> 节中的第一个脚本,以便它可以监视所有依赖项存在的任何潜在问题或任何 JavaScript 问题。Preferably, it should be the first script in your <head> section so that it can monitor any potential issues with all of your dependencies and optionally any JavaScript errors. 如果使用的是 Blazor Server 应用,请在文件 _Host.cshtml 的顶部 <head> 部分中添加代码片段。If you are using Blazor Server App, add the snippet at the top of the file _Host.cshtml in the <head> section.

为了帮助跟踪应用程序使用的代码片段版本,从版本 2.5.5 开始,页面视图事件将包含一个新的标记“ai.internal.snippet”,该标记将包含标识的代码片段版本。To assist with tracking which version of the snippet your application is using, starting from version 2.5.5 the page view event will include a new tag "ai.internal.snippet" that will contain the identified snippet version.

当前代码片段(如下所示)将标识为版本“3”。The current Snippet (listed below) will be identified as version "3".

<script type="text/javascript">
!function(T,l,y){var S=T.location,u="script",k="instrumentationKey",D="ingestionendpoint",C="disableExceptionTracking",E="ai.device.",I="toLowerCase",b="crossOrigin",w="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"4",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[I](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.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}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,p,l,u;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][I]()]=i[1])}if(!e[D]){var r=e.endpointsuffix,o=r?e.location:null;e[D]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[k]||d[k]||"",p=s[D],l=p?p+"/v2/track":config.endpointUrl,(u=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=l,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),u.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,l)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:w,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(w,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(u,l))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(u);n.src=h;var e=y[b];return!e&&""!==e||"undefined"==n[b]||(n[b]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(u)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[C]&&!0!==s[C]){method="onerror",t(["_"+method]);var c=T[method];T[method]=function(e,t,n,a,i){var r=c&&c(e,t,n,a,i);return!0!==r&&m["_"+method]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);(T[t]=n).queue&&0===n.queue.length&&n.trackPageView({})}(window,document,{
src: "https://az416426.vo.msecnd.net/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 
cfg: { // Application Insights Configuration
    /* ...Other Configuration Options... */


为了提高可读性并减少可能的 JavaScript 错误,在上述代码片段的新行上列出了所有可能的配置选项,如果不希望更改注释行的值,可以将其删除。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 failures

此版本的代码片段检测并报告在将 SDK 作为扩展从 CDN 加载到 Azure Monitor 门户时出现的故障(在“故障”>“异常”>“浏览器”下),此异常提供此类故障的可见性,使你知道应用程序不会按预期方式报告遥测(或其他异常)。This version of the snippet detects and reports failures when loading the SDK from the CDN as an exception to the Azure Monitor portal (under the failures > exceptions > browser), this exception provides visibility into failures of this type so that you are aware that your application is not reporting telemetry (or other exceptions) as expected. 此信号对于了解以下情况至关重要:由于未加载或初始化 SDK,因此缺少遥测数据,这可能导致:This signal is an important measurement in understanding that you have lost telemetry because the SDK did not load or initialize which can lead to:

  • 漏报用户使用(或尝试使用)站点的方式;Under-reporting of how users are using (or trying to use) your site;
  • 缺少关于最终用户使用站点的方式的遥测数据;Missing telemetry on how your end users are using your site;
  • 遗漏可能阻止最终用户成功使用站点的 JavaScript 错误。Missing JavaScript errors that could potentially be blocking your end users from successfully using your site.

有关此异常的详细信息,请参阅 SDK 加载失败疑难解答页面。For details on this exception see the SDK load failure troubleshooting page.

将此失败作为门户异常进行报告时不会使用 Application Insights 配置中的 disableExceptionTracking 配置选项,因此,如果发生此失败,则将始终通过代码片段进行报告,即使禁用了 window.onerror 支持也是如此。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.

IE 8(或更低版本)尤其不支持报告 SDK 加载失败。Reporting of SDK load failures is specifically NOT supported on IE 8 (or less). 假设大多数环境都不仅仅是 IE 8 或更低版本,这有助于减少代码片段的缩小版大小。This assists with reducing the minified size of the snippet by assuming that most environments are not exclusively IE 8 or less. 如果你有此要求并且希望收到这些异常,则需要包括 fetch polyfill,或创建自己的代码片段版本,使其使用 XDomainRequest 而不是 XMLHttpRequest,建议使用提供的代码片段源代码作为起点。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.


如果你使用的是早期版本的代码片段,则强烈建议你更新到最新版本,以便收到以前未报告的问题。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

现在,所有配置选项都已移到脚本的末尾,以避免意外引入 JavaScript 错误,这类错误不仅会导致 SDK 加载失败,而且还会阻止报告此失败。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
srcsrc 字符串 [必需]string [required] 要从中加载 SDK 的完整 URL。The full URL for where to load the SDK from. 此值用于动态添加的 <script /> 标记的“src”属性。This value is used for the "src" attribute of a dynamically added <script /> tag. 你可以使用公共 CDN 位置,也可以使用自己的私有托管位置。You can use the public CDN location or your own privately hosted one.
namename 字符串 [可选]string [optional] 已初始化的 SDK 的全局名称,默认值为 appInsights。The global name for the initialized SDK, defaults to appInsights. 因此 window.appInsights 将是对已初始化实例的引用。So window.appInsights will be a reference to the initialized instance. 注意:如果提供一个名称值或上一个实例似乎是通过全局名称 appInsightsSDK 分配的,则此名称值也将在全局命名空间中定义为 window.appInsightsSDK=<name value>,SDK 初始化代码需要此名称,以确保它正在初始化和更新的代码片段主干和代理方法正确。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.
ldld 毫秒数 [可选]number in ms [optional] 定义在尝试加载 SDK 之前要等待的加载延迟。Defines the load delay to wait before attempting to load the SDK. 默认值为 0 毫秒,任何负值都表示将立即向页面的 <head> 区域添加脚本标记,然后在加载脚本(或失败)之前阻止页面加载事件。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).
useXhruseXhr 布尔 [可选]boolean [optional] 此设置仅用于报告 SDK 加载失败。This setting is used only for reporting SDK load failures. 报告将首先尝试使用 fetch()(如果可用),然后回退到 XHR,将此值设置为 true 即可绕过提取检查。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.
crossOrigincrossOrigin 字符串 [可选]string [optional] 通过包含此设置,添加以下载 SDK 的脚本标记将包含带有此字符串值的 crossOrigin 属性。By including this setting, the script tag added to download the SDK will include the crossOrigin attribute with this string value. 如果未定义(默认值),则不添加 crossOrigin 属性。When not defined (the default) no crossOrigin attribute is added. 未定义建议的值(默认值);""; 或“anonymous”(如需了解所有有效值,请参阅 HTML 属性:crossorigin 文档)Recommended values are not defined (the default); ""; or "anonymous" (For all valid values see HTML attribute: crossorigin documentation)
cfgcfg 对象 [必需]object [required] 初始化期间传递到 Application Insights SDK 的配置。THe configuration passed to the Application Insights SDK during initialization.

将遥测数据发送到 Azure 门户Sending telemetry to the Azure portal

默认情况下,Application Insights JavaScript SDK 会自动收集许多遥测项,这些项有助于确定应用程序和底层用户体验的运行状况。By default the Application Insights JavaScript SDK autocollects a number of telemetry items that are helpful in determining the health of your application and the underlying user experience. 其中包括:These include:

  • 应用中未捕获到的异常,包括以下相关信息Uncaught exceptions in your app, including information on
    • 堆栈跟踪Stack trace
    • 异常详细信息和错误随附的消息Exception details and message accompanying the error
    • 错误的行号与列号Line & column number of error
    • 引发错误的 URLURL where error was raised
  • 应用发出的网络依赖项请求XHRFETCH(默认已禁用提取集合)请求,包括以下相关信息Network Dependency Requests made by your app XHR and Fetch (fetch collection is disabled by default) requests, include information on
    • 依赖项源的 URLUrl of dependency source
    • 用于请求依赖项的命令和方法Command & Method used to request the dependency
    • 请求持续时间Duration of the request
    • 请求的结果代码和成功状态Result code and success status of the request
    • 发出请求的用户的 ID(如果有)ID (if any) of user making the request
    • 发出请求的关联上下文(如果有)Correlation context (if any) where request is made
  • 用户信息(例如位置、网络、IP)User information (for example, Location, network, IP)
  • 设备信息(例如,浏览器、OS、版本、语言、型号)Device information (for example, 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. 它们还可用于返回 false 以阻止发送某些遥测数据。They can also be used to prevent certain telemetry from being sent, by returning false. 可将多个遥测初始化表达式添加到 Application Insights 实例,它们将按添加顺序执行。Multiple telemetry initializers can be added to your Application Insights instance, and they are executed in order of adding them.

addTelemetryInitializer 的输入参数是一个回调,该回调采用 ITelemetryItem 作为参数,并返回 booleanvoidThe input argument to addTelemetryInitializer is a callback that takes a ITelemetryItem as an argument and returns a boolean or void. 如果返回 false,则不发送遥测项,否则将继续处理下一个遥测初始化表达式(如果有),或者将遥测项发送到遥测集合终结点。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.

使用遥测初始化表达式的示例:An example of using telemetry initializers:

var telemetryInitializer = (envelope) => {
  envelope.data.someField = 'This item passed through my telemetry initializer';
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


大多数配置字段的命名都可默认为 false。Most configuration fields are named such that they can be defaulted to false. instrumentationKey 以外的所有字段都是可选的。All fields are optional except for instrumentationKey.

名称Name 默认Default 说明Description
instrumentationKeyinstrumentationKey Nullnull 必需Required
从 Azure 门户获取的检测密钥。Instrumentation key that you obtained from the Azure portal.
accountIdaccountId Nullnull 可选的帐户 ID(如果应用将用户分组到帐户中)。An optional account ID, if your app groups users into accounts. 不允许使用空格、逗号、分号、等于或竖线No spaces, commas, semicolons, equals, or vertical bars
sessionRenewalMssessionRenewalMs 18000001800000 如果用户处于非活动状态有这么长的时间(以毫秒为单位),则会记录会话。A session is logged if the user is inactive for this amount of time in milliseconds. 默认值为 30 分钟Default is 30 minutes
sessionExpirationMssessionExpirationMs 8640000086400000 如果会话持续了这么长的时间(以毫秒为单位),则会记录会话。A session is logged if it has continued for this amount of time in milliseconds. 默认值为 24 小时Default is 24 hours
maxBatchSizeInBytesmaxBatchSizeInBytes 1000010000 遥测批的最大大小。Max size of telemetry batch. 如果某个批超过此限制,则立即发送此批,并启动新批If a batch exceeds this limit, it is immediately sent and a new batch is started
maxBatchIntervalmaxBatchInterval 1500015000 发送前要批处理遥测数据的时间长短(毫秒)How long to batch telemetry for before sending (milliseconds)
disableExceptionTrackingdisableExceptionTracking falsefalse 如果为 true,则不自动收集异常。If true, exceptions are no autocollected. 默认值为 false。Default is false.
disableTelemetrydisableTelemetry falsefalse 如果为 true,则不收集或发送遥测数据。If true, telemetry is not collected or sent. 默认值为 false。Default is false.
enableDebugenableDebug falsefalse 如果为 true,则不管 SDK 日志记录设置如何,内部调试数据都将引发为异常,而不是记录这些数据。If true, internal debugging data is thrown as an exception instead of being logged, regardless of SDK logging settings. 默认值为 false。Default is false.
注意: 如果启用此设置,每当发生内部错误时,都会导致丢弃遥测数据。Note: Enabling this setting will result in dropped telemetry whenever an internal error occurs. 这可能有利于快速识别 SDK 的配置或用法问题。This can be useful for quickly identifying issues with your configuration or usage of the SDK. 如果你不希望在调试时丢失遥测数据,请考虑使用 consoleLoggingLeveltelemetryLoggingLevel,而不是 enableDebugIf you do not want to lose telemetry while debugging, consider using consoleLoggingLevel or telemetryLoggingLevel instead of enableDebug.
loggingLevelConsoleloggingLevelConsole 00 内部 Application Insights 错误记录到控制台。Logs internal Application Insights errors to console.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
loggingLevelTelemetryloggingLevelTelemetry 11 内部 Application Insights 错误作为遥测数据发送。Sends internal Application Insights errors as telemetry.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
diagnosticLogIntervaldiagnosticLogInterval 1000010000 内部日志记录队列的(内部)轮询间隔(以毫秒为单位)(internal) Polling interval (in ms) for internal logging queue
samplingPercentagesamplingPercentage 100100 要发送的事件百分比。Percentage of events that will be sent. 默认值为 100,表示发送所有事件。Default is 100, meaning all events are sent. 如果你希望避免大型应用程序达到数据上限,请设置此项。Set this if you wish to preserve your data cap for large-scale applications.
autoTrackPageVisitTimeautoTrackPageVisitTime falsefalse 如果为 true,则对于页面视图,将跟踪前一个检测的页面的查看时间并将其作为遥测数据发送,同时,为当前的页面视图启动新的计时器。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. 默认值为 false。Default is false.
disableAjaxTrackingdisableAjaxTracking falsefalse 如果为 true,则不自动收集 Ajax 调用。If true, Ajax calls are not autocollected. 默认值为 false。Default is false.
disableFetchTrackingdisableFetchTracking true 如果为 true,则不自动收集 Fetch 请求。If true, Fetch requests are not autocollected. 默认值为 trueDefault is true
overridePageViewDurationoverridePageViewDuration falsefalse 如果为 true,则在调用 trackPageView 时,trackPageView 的默认行为将更改为记录页面视图持续时间间隔的结束时间。If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. 如果为 false 且未为 trackPageView 提供自定义持续时间,则会使用导航计时 API 计算页面视图性能。If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. 默认值为 false。Default is false.
maxAjaxCallsPerViewmaxAjaxCallsPerView 500500 默认值为 500 - 控制每个页面视图将监视多少个 Ajax 调用。Default 500 - controls how many Ajax calls will be monitored per page view. 设置为 -1 可监视页面上的所有(无限制)Ajax 调用。Set to -1 to monitor all (unlimited) Ajax calls on the page.
disableDataLossAnalysisdisableDataLossAnalysis true 如果为 false,则对于尚未发送的项,启动时将检查内部遥测发送方缓冲区。If false, internal telemetry sender buffers will be checked at startup for items not yet sent.
disableCorrelationHeadersdisableCorrelationHeaders falsefalse 如果为 false,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有依赖项请求,以将其关联到服务器端上的对应请求。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. 默认值为 false。Default is false.
correlationHeaderExcludedDomainscorrelationHeaderExcludedDomains 禁用特定域的关联标头Disable correlation headers for specific domains
correlationHeaderDomainscorrelationHeaderDomains 启用特定域的关联标头Enable correlation headers for specific domains
disableFlushOnBeforeUnloaddisableFlushOnBeforeUnload falsefalse 默认值为 false。Default false. 如果为 true,则触发 onBeforeUnload 事件时不会调用 flush 方法If true, flush method will not be called when onBeforeUnload event triggers
enableSessionStorageBufferenableSessionStorageBuffer true 默认值为 true。Default true. 如果为 true,则会将包含所有未发送的遥测数据的缓冲区存储在会话存储中。If true, the buffer with all unsent telemetry is stored in session storage. 加载页面时会还原该缓冲区The buffer is restored on page load
isCookieUseDisabledisCookieUseDisabled falsefalse 默认值为 false。Default false. 如果为 true,则 SDK 不会存储或读取 Cookie 中的任何数据。If true, the SDK will not store or read any data from cookies.
cookieDomaincookieDomain Nullnull 自定义 Cookie 域。Custom cookie domain. 若要跨子域共享 Application Insights Cookie,此字段会有帮助。This is helpful if you want to share Application Insights cookies across subdomains.
isRetryDisabledisRetryDisabled falsefalse 默认值为 false。Default false. 如果为 false,则出现代码 206(部分成功)、408(超时)、429(请求过多)、500(内部服务器错误)、503(服务不可用)和 0(脱机,仅当已检测到此状态时)时会重试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)
isStorageUseDisabledisStorageUseDisabled falsefalse 如果为 true,则 SDK 不会存储或读取本地和会话存储中的任何数据。If true, the SDK will not store or read any data from local and session storage. 默认值为 false。Default is false.
isBeaconApiDisabledisBeaconApiDisabled true 如果为 false,则 SDK 将使用信标 API 发送所有遥测数据If false, the SDK will send all telemetry using the Beacon API
onunloadDisableBeacononunloadDisableBeacon falsefalse 默认值为 false。Default false. 选项卡关闭时,SDK 将使用信标 API 发送所有剩余的遥测when tab is closed, the SDK will send all remaining telemetry using the Beacon API
sdkExtensionsdkExtension Nullnull 设置 SDK 扩展名。Sets the sdk extension name. 仅允许使用字母字符。Only alphabetic characters are allowed. 扩展名将添加为“ai.internal.sdkVersion”标记的前缀(例如“ext_javascript:2.0.0”)。The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (for example, 'ext_javascript:2.0.0'). 默认值为 null。Default is null.
isBrowserLinkTrackingEnabledisBrowserLinkTrackingEnabled falsefalse 默认值为 false。Default is false. 如果为 true,则 SDK 将跟踪所有浏览器链接请求。If true, the SDK will track all Browser Link requests.
appIdappId Nullnull appId 用于在客户端上发生的 AJAX 依赖项与服务器端请求之间进行关联。AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. 启用信标 API 后,无法自动使用 appId,但可以在配置中手动设置它。When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. 默认值为 nullDefault is null
enableCorsCorrelationenableCorsCorrelation falsefalse 如果为 true,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有 CORS 请求,以将传出的 AJAX 依赖项关联到服务器端上的对应请求。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. 默认值为 falseDefault is false
namePrefixnamePrefix undefinedundefined 一个可选值,用作 localStorage 和 Cookie 名称的名称后缀。An optional value that will be used as name postfix for localStorage and cookie name.
enableAutoRouteTrackingenableAutoRouteTracking falsefalse 自动跟踪单页应用程序 (SPA) 中的路由更改。Automatically track route changes in Single Page Applications (SPA). 如果为 true,则每次更改路由都会将一个新的页面视图发送到 Application Insights。If true, each route change will send a new Pageview to Application Insights. 哈希路由更改 (example.com/foo#bar) 也会记录为新的页面视图。Hash route changes (example.com/foo#bar) are also recorded as new page views.
enableRequestHeaderTrackingenableRequestHeaderTracking falsefalse 如果为 true,则跟踪 AJAX 和 Fetch 请求标头,默认值为 false。If true, AJAX & Fetch request headers is tracked, default is false.
enableResponseHeaderTrackingenableResponseHeaderTracking falsefalse 如果为 true,则跟踪 AJAX 和 Fetch 请求的响应标头,默认值为 false。If true, AJAX & Fetch request's response headers is tracked, default is false.
distributedTracingModedistributedTracingMode DistributedTracingModes.AI 设置分布式跟踪模式。Sets the distributed tracing mode. 如果设置了 AI_AND_W3C 模式或 W3C 模式,则将生成 W3C 跟踪上下文标头 (traceparent/tracestate),并将其包含在所有传出请求中。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 是为了与任何旧版 Application Insights 检测服务向后兼容。AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services. 请参阅此处的示例。See example here.
enableAjaxErrorStatusTextenableAjaxErrorStatusText falsefalse 默认值为 false。Default false. 如果为 true,则在 AJAX 请求失败时包含依赖关系事件中的响应错误数据文本。If true, include response error data text in dependency event on failed AJAX requests.
enableAjaxPerfTrackingenableAjaxPerfTracking falsefalse 默认值为 false。Default false. 用于启用查找并包含报告的 ajax(XHR 和 fetch)报告的指标中其他浏览器 window.performance 计时的标记。Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics.
maxAjaxPerfLookupAttemptsmaxAjaxPerfLookupAttempts 33 默认值为 3。Defaults to 3. 查找 window.performance 计时的最大次数,此值为必需,因为并非所有浏览器在报告 XHR 请求完成之前都会填充 window.performance,而对于 fetch 请求,将在请求完成之后添加该值。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.
ajaxPerfLookupDelayajaxPerfLookupDelay 2525 默认值为 25 毫秒。Defaults to 25 ms. 重新尝试为 ajax 请求查找 windows.performance 计时时要等待的时间,时间以毫秒计并直接传递给 setTimeout()。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().
enableUnhandledPromiseRejectionTrackingenableUnhandledPromiseRejectionTracking falsefalse 如果为 true,则将自动收集未处理的拒绝承诺并报告为 JavaScript 错误。If true, unhandled promise rejections will be autocollected and reported as a JavaScript error. 如果 disableExceptionTracking 为 true(不跟踪异常),则将忽略配置值且不会报告未处理的拒绝承诺。When disableExceptionTracking is true (don't track exceptions), the config value will be ignored and unhandled promise rejections will not be reported.

单页应用程序Single Page Applications

默认情况下,此 SDK 不会处理单页应用程序中发生的基于状态的路由更改。By default, this SDK will not handle state-based route changing that occurs in single page applications. 若要为单页应用程序启用自动路由更改跟踪,可将 enableAutoRouteTracking: true 添加到设置配置。To enable automatic route change tracking for your single page application, you can add enableAutoRouteTracking: true to your setup configuration.

目前,我们提供了一个单独的 React 插件(可以使用此 SDK 对其进行初始化)。Currently, we offer a separate React plugin, which you can initialize with this SDK. 该插件也能为你实现路由更改跟踪,并可收集其他特定于 React 的遥测数据It will also accomplish route change tracking for you, as well as collect other React specific telemetry.


仅当你不使用 React 插件时,才使用 enableAutoRouteTracking: trueUse enableAutoRouteTracking: true only if you are not using the React plugin. 当路由更改时,这两种方法都能发送新的 PageView。Both are capable of sending new PageViews when the route changes. 如果这两种方法均已启用,则可能会发送重复的 PageView。If both are enabled, duplicate PageViews may be sent.

配置:autoTrackPageVisitTimeConfiguration: autoTrackPageVisitTime

通过设置 autoTrackPageVisitTime: true,跟踪用户在每个页面上花费的时间。By setting autoTrackPageVisitTime: true, the time a user spends on each page is tracked. 在每个新的 PageView 上,用户在上一页花费的时间将作为名为 PageVisitTime 的自定义指标发送。On each new PageView, the duration the user spent on the previous page is sent as a custom metric named PageVisitTime. 此自定义指标可在指标资源管理器中作为“基于日志的指标”查看。This custom metric is viewable in the Metrics Explorer as a "log-based metric".

React 扩展React extensions

React NativeReact Native

浏览浏览器/客户端数据Explore browser/client-side data

可以转到“指标”并添加你感兴趣的各个指标,来查看浏览器/客户端数据:Browser/client-side data can be viewed by going to Metrics and adding individual metrics you are interested in:

还可以通过门户中的“浏览器”体验查看 JavaScript SDK 中的数据。You can also view your data from the JavaScript SDK via the Browser experience in the portal.

选择“浏览器”,然后选择“失败”或“性能”。Select Browser and then choose Failures or Performance.




若要查询 JavaScript SDK 收集的遥测数据,请选择“在日志(分析)中查看”按钮。To query your telemetry collected by the JavaScript SDK, select the View in Logs (Analytics) button. 如果添加 client_Type == "Browser"where 语句,则只会看到来自 JavaScript SDK 的数据,而其他 SDK 收集的任何服务器端遥测数据将被排除。By adding a where statement of client_Type == "Browser", you will only see data from the JavaScript SDK and any server-side telemetry collected by other SDKs will be excluded.

// average pageView duration by name
let timeGrain=5m;
let dataset=pageViews
// additional filters can be applied here
| where timestamp > ago(1d)
| where client_Type == "Browser" ;
// calculate average pageView duration for all pageViews
| summarize avg(duration) by bin(timestamp, timeGrain)
| extend pageView='Overall'
// render result in a chart
| render timechart

源映射支持Source Map Support

可以在 Azure 门户中取消缩小异常遥测的已缩小调用堆栈。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.

可以将 Application Insights 资源链接到自己的 Azure Blob 存储容器,以便自动取消缩小调用堆栈。You can link your Application Insights resource to your own Azure Blob Storage container to automatically unminify call stacks. 若要开始,请参阅自动源映射支持To get started, see automatic source map support.

拖放Drag and drop

  1. 请在 Azure 门户中选择一个异常遥测项,以查看其“端到端事务详细信息”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. 源映射必须与堆栈帧的源文件相匹配,但后缀为 .mapThe source map must match a stack frame's source file, but suffixed with .map
  3. 将源映射拖放到 Azure 门户中的调用堆栈上 Drag and drop the source maps onto the call stack in the Azure portal

Application Insights Web 基本版Application Insights Web Basic

若要获得精简的体验,可以改为安装基本版 Application InsightsFor 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 number of features and functionalities and relies on you to build it up as you see fit. 例如,它不执行自动收集(未捕获的异常、AJAX 等等)。For example, it performs no autocollection (uncaught exceptions, AJAX, etc.). 此版本不包含用于发送某些遥测类型的 API(例如 trackTracetrackException 等),因此你需要提供自己的包装器。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. 提供的唯一 API 是 trackThe only API that is available is track. 此处提供了一个示例。A sample is located here.


有关可运行的示例,请参阅 Application Insights JavaScript SDK 示例For runnable examples, see Application Insights JavaScript SDK Samples

从旧版 Application Insights 升级Upgrading from the old version of Application Insights

SDK V2 版本中的重大更改:Breaking changes in the SDK V2 version:

  • 为了让用户生成更好的 API 签名,某些 API 调用(例如 trackPageView 和 trackException)已更新。To allow for better API signatures, some of the API calls, such as trackPageView and trackException, have been updated. 不支持在 Internet Explorer 8 和早期版本的浏览器中运行。Running in Internet Explorer 8 and earlier versions of the browser is not supported.
  • 由于数据架构更新,遥测信封的字段名称和结构已更改。The telemetry envelope has field name and structure changes due to data schema updates.
  • 已将 context.operation 转移到 context.telemetryTraceMoved context.operation to context.telemetryTrace. 此外还更改了一些字段 (operation.id --> telemetryTrace.traceID)。Some fields were also changed (operation.id --> telemetryTrace.traceID).
    • 若要手动刷新当前页面视图 ID(例如,在 SPA 应用中这样做),请使用 appInsights.properties.context.telemetryTrace.traceID = Util.generateW3CId()To manually refresh the current pageview ID (for example, in SPA apps), use appInsights.properties.context.telemetryTrace.traceID = Util.generateW3CId().


      为了使跟踪 ID 独一无二,以前使用 Util.newId(),现在使用 Util.generateW3CId()To keep the trace ID unique, where you previously used Util.newId(), now use Util.generateW3CId(). 二者最终都会成为操作 ID。Both ultimately end up being the operation ID.

如果你正在使用最新的 Application Insights PRODUCTION SDK (1.0.20),并想要查看新 SDK 是否可在运行时中正常工作,请根据当前的 SDK 加载方案更新 URL。If you're using the current application insights PRODUCTION SDK (1.0.20) and want to see if the new SDK works in runtime, update the URL depending on your current SDK loading scenario.

  • 通过 CDN 方案下载:更新当前用于指向以下 URL 的代码片段:Download via CDN scenario: Update the code snippet that you currently use to point to the following URL:

  • npm 方案:调用 downloadAndSetup 以从 CDN 下载完整的 ApplicationInsights 脚本,并使用检测密钥将其初始化:npm scenario: Call downloadAndSetup to download the full ApplicationInsights script from CDN and initialize it with instrumentation key:

       instrumentationKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
       url: "https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js"

在内部环境中进行测试,以验证是否可按预期方式监视遥测。Test in internal environment to verify monitoring telemetry is working as expected. 如果一切正常,请相应地将 API 签名更新为 SDK V2 版本,并部署到生产环境中。If all works, update your API signatures appropriately to SDK V2 version and deploy in your production environments.

SDK 性能/开销SDK performance/overhead

经过 gzip 压缩后只有 36 KB,只需大约 15 毫秒即可完成初始化,Application Insights 在网站中的加载时间可忽略不计。At just 36 KB gzipped, and taking only ~15 ms to initialize, Application Insights adds a negligible amount of loadtime 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.

从 CDN 下载脚本时,页面的所有跟踪将会排队。While the script is downloading 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.


  • npm 版本
  • gzip 压缩大小
  • 总初始化时间为 15 毫秒15 ms overall initialization time
  • 在页面的整个生命周期内都不会失去跟踪Zero tracking missed during life cycle of page

浏览器支持Browser support

Chrome Firefox IE Opera Safari
Chrome 最新版 ✔Chrome Latest ✔ Firefox 最新版 ✔Firefox Latest ✔ IE 9 + 和 Microsoft Edge ✔IE 9+ & Edge ✔
IE 8- 兼容IE 8- Compatible
Opera 最新版 ✔Opera Latest ✔ Safari 最新版 ✔Safari Latest ✔

ES3/IE8 兼容性ES3/IE8 Compatibility

作为 SDK,很多用户无法控制其客户所使用的浏览器。As an SDK there are numerous users that cannot control the browsers that their customers use. 因此,我们需要确保此 SDK 继续“工作”,并且在由旧版浏览器加载时不会中断 JS 执行。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. 虽然可以选择不支持 IE8 和旧版生成 (ES3) 浏览器,但有很多大型客户/用户会继续要求页面“工作”,并且我们发现,他们可能或无法控制其最终用户选择使用的浏览器。While it would be ideal to 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.

这并不意味着我们只支持最少的一组常见功能,只是我们需要维护 ES3 代码兼容性,并且需要采用一种既不会中断 ES3 JavaScript 分析又可作为可选功能进行添加的方式来添加新功能。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.

有关 IE8 支持的完整详细信息,请参阅 GitHubSee GitHub for full details on IE8 support

开源 SDKOpen-source SDK

Application Insights JavaScript SDK 是开源的,用户可查看其源代码;若要对该项目做贡献,请访问官方 GitHub 存储库The Application Insights JavaScript SDK is open-source to view the source code or to contribute to the project visit the official GitHub repository.

后续步骤Next steps