適用於網頁的 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. 這些項目可以依據頁面、用戶端作業系統和瀏覽器版本、地區位置和其他維度分割。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


新的 Azure 區域 需要 使用連接字串,而不是檢測金鑰。New Azure regions require the use of connection strings instead of instrumentation keys. 連接字串 會識別您想要與遙測資料相關聯的資源。Connection string identifies the resource that you want to associate your telemetry data with. 它也可讓您修改您的資源將用來做為遙測目的地的端點。It also allows you to modify the endpoints your resource will use as a destination for your telemetry. 您必須複製連接字串,並將它加入應用程式的程式碼或加入環境變數。You will need to copy the connection string and add it to your application's code or to an environment variable.

  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. 檢測金鑰 ( (也稱為 "iKey")複製到您要從中傳送 JavaScript 遙測 (之資源的 ) 或 連接字串 。 ) 您會將它新增至 instrumentationKey connectionString Application Insights JavaScript SDK 的或設定。Copy the instrumentation key (also known as "iKey") or connection string for the resource where you want your JavaScript telemetry to be sent (from step 1.) You will add it to the instrumentationKey or connectionString 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 套件。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 開始,網頁檢視事件將包含新的標記 "",其中將包含所識別的程式碼片段版本。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.

下列 (目前的程式碼片段) 為版本 "5",版本在程式碼片段中編碼為 sv: "#",且 目前版本也可在 GitHub 上取得。The current Snippet (listed below) is version "5", the version is encoded in the snippet as sv:"#" and the current version is also available on GitHub.

<script type="text/javascript">
!function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="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:"5",version:2,config:d};function v(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_"+(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,u,p,l;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][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(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)),l.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,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=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(k)[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[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[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
    /* ...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 監視器入口網站 (例外狀況瀏覽器) 下的例外狀況 > > ,此例外狀況可讓您知道您的應用程式未如預期般報告遙測 (或其他) 例外狀況。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 ,因此,如果發生此失敗,則即使在視窗中停用 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 poly 填滿或建立使用的程式碼片段版本( 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

所有設定選項現在都已移至腳本的結尾,以協助避免意外引進不會導致 SDK 無法載入的 JavaScript 錯誤,同時也會停用失敗的報告。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. 此值可用於動態新增之腳本/標記的 "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 的全域名稱,預設為 appInsightsThe 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 初始化程式碼所需的值,以確保其初始化和更新正確的程式碼片段基本架構和 proxy 方法。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毫秒,任何負值都會立即將腳本標記新增至頁面的 < 前端 > 區域,然後會封鎖頁面載入事件,直到載入腳本 (或) 失敗為止。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. 報告將會先嘗試使用提取 () 如果可用,然後再回到 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. 建議的值 (預設) 不會定義;"";或「匿名」 (所有有效值的詳細資料,請參閱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.

連接字串設定Connection String Setup

針對 NPM 或程式碼片段的設定,您也可以使用連接字串來設定 Application Insights 的實例。For either the NPM or Snippet setup, you can also configure your instance of Application Insights using a Connection String. 只要 instrumentationKey 以欄位取代欄位即可 connectionStringSimply replace the instrumentationKey field with the connectionString field.

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

const appInsights = new ApplicationInsights({ config: {
  /* ...Other Configuration Options... */
} });

將遙測傳送至 Azure 入口網站Sending telemetry to the Azure portal

根據預設,Application Insights JavaScript SDK 會 autocollects 許多遙測專案,這些專案有助於判斷您的應用程式和基礎使用者體驗的健康情況。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
  • 依預設會停用您的應用程式 XHR提取 (提取集合所提出的網路相依性 要求,) 的要求,包含相關資訊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 (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. 您也可以藉由傳回來使用它們來防止傳送某些遙測資料 falseThey 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 做為引數並傳回或的回呼 boolean voidThe 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. 除了以外,所有欄位都是選擇性的 instrumentationKeyAll fields are optional except for instrumentationKey.

NameName 描述Description 預設Default
instrumentationKeyinstrumentationKey 必要Required
您從 Azure 入口網站取得的檢測金鑰。Instrumentation key that you obtained from the Azure portal.
accountIdaccountId 如果您的應用程式將使用者群組為帳戶,則為選擇性的帳戶識別碼。An optional account ID, if your app groups users into accounts. 沒有空格、逗號、分號、等於或分隔號No spaces, commas, semicolons, equals, or vertical bars 字串string
sessionRenewalMssessionRenewalMs 如果使用者在這段時間內處於非使用中狀態,則會記錄會話(以毫秒為單位)。A session is logged if the user is inactive for this amount of time in milliseconds. NUMERICnumeric
(30 分鐘) (30 mins)
sessionExpirationMssessionExpirationMs 如果會話已繼續此時間量(以毫秒為單位),則會記錄會話。A session is logged if it has continued for this amount of time in milliseconds. NUMERICnumeric
(24 小時) (24 hours)
maxBatchSizeInBytesmaxBatchSizeInBytes 遙測批次的大小上限。Max size of telemetry batch. 如果批次超過此限制,則會立即傳送並啟動新的批次If a batch exceeds this limit, it is immediately sent and a new batch is started NUMERICnumeric
maxBatchIntervalmaxBatchInterval 傳送 (毫秒之前,批次遙測的時間長度) How long to batch telemetry for before sending (milliseconds) NUMERICnumeric
停用​ExceptionTrackingdisable​ExceptionTracking 若為 true,則不會實驗自動收集例外狀況。If true, exceptions are not autocollected. booleanboolean
disableTelemetrydisableTelemetry 若為 true,則不會收集或傳送遙測。If true, telemetry is not collected or sent. booleanboolean
enableDebugenableDebug 若為 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. 如果您不想在進行偵錯工具時遺失遙測,請考慮使用 consoleLoggingLevel 或, telemetryLoggingLevel 而不是 enableDebugIf you do not want to lose telemetry while debugging, consider using consoleLoggingLevel or telemetryLoggingLevel instead of enableDebug.
loggingLevelConsoleloggingLevelConsole 內部 Application Insights 錯誤記錄到主控台。Logs internal Application Insights errors to console.
0:關閉、0: off,
1:僅嚴重錯誤,1: Critical errors only,
2:所有 (錯誤 & 警告) 2: Everything (errors & warnings)
loggingLevelTelemetryloggingLevelTelemetry 以遙測的形式傳送 內部 Application Insights 錯誤。Sends internal Application Insights errors as telemetry.
0:關閉、0: off,
1:僅嚴重錯誤,1: Critical errors only,
2:所有 (錯誤 & 警告) 2: Everything (errors & warnings)
diagnosticLogIntervaldiagnosticLogInterval 內部記錄佇列的 (內部) 輪詢間隔 (毫秒) (internal) Polling interval (in ms) for internal logging queue NUMERICnumeric
samplingPercentagesamplingPercentage 將傳送的事件百分比。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. NUMERICnumeric
autoTrackPageVisitTimeautoTrackPageVisitTime 若為 true,則在 pageview 上,會追蹤先前檢測的網頁檢視時間,並將其傳送為遙測,並為目前的 pageview 啟動新的計時器。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. booleanboolean
disableAjaxTrackingdisableAjaxTracking 若為 true,則不會實驗自動收集 Ajax 呼叫。If true, Ajax calls are not autocollected. booleanboolean
disableFetchTrackingdisableFetchTracking 若為 true,則不會實驗自動收集提取要求。If true, Fetch requests are not autocollected. booleanboolean
overridePageViewDurationoverridePageViewDuration 若為 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. booleanboolean
maxAjaxCallsPerViewmaxAjaxCallsPerView 預設值 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. NUMERICnumeric
disableDataLossAnalysisdisableDataLossAnalysis 如果為 false,則會在啟動時檢查尚未傳送之專案的內部遙測傳送者緩衝區。If false, internal telemetry sender buffers will be checked at startup for items not yet sent. booleanboolean
停用​CorrelationHeadersdisable​CorrelationHeaders 若為 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. booleanboolean
correlationHeader​ExcludedDomainscorrelationHeader​ExcludedDomains 停用特定網域的相互關聯標頭Disable correlation headers for specific domains string[]string[]
correlationHeader​ExcludePatternscorrelationHeader​ExcludePatterns 使用正則運算式停用相互關聯標頭Disable correlation headers using regular expressions RegEx []regex[]
correlationHeader​網域correlationHeader​Domains 啟用特定網域的相互關聯標頭Enable correlation headers for specific domains string[]string[]
disableFlush​OnBeforeUnloaddisableFlush​OnBeforeUnload 若為 true,onBeforeUnload 事件觸發程式時,將不會呼叫 flush 方法If true, flush method will not be called when onBeforeUnload event triggers booleanboolean
enableSessionStorageBufferenableSessionStorageBuffer 若為 true,則會將包含所有未傳送遙測的緩衝區儲存在會話儲存體中。If true, the buffer with all unsent telemetry is stored in session storage. 在頁面載入時還原緩衝區The buffer is restored on page load booleanboolean
cookieCfgcookieCfg 預設為啟用 cookie 使用方式,請參閱 ICookieCfgConfig 設定以取得完整的預設值。Defaults to cookie usage enabled see ICookieCfgConfig settings for full defaults. ICookieCfgConfigICookieCfgConfig
(自 2.6.0) (Since 2.6.0)
若為 true,SDK 將不會儲存或讀取 cookie 中的任何資料。If true, the SDK will not store or read any data from cookies. 請注意,這會停用使用者和會話 cookie,並將使用方式的 blade 和體驗呈現為無用。Note that this disables the User and Session cookies and renders the usage blades and experiences useless. isCookieUseDisable 已被取代為 disableCookiesUsage,當提供兩者時,disableCookiesUsage 會優先使用。isCookieUseDisable is deprecated in favor of disableCookiesUsage, when both are provided disableCookiesUsage takes precedence.
(由於 v 2.6.0) ,而且如果 cookieCfg.enabled 也定義了此值,就會優先使用這些值,在初始化之後,您可以透過 getCookieMgr () setEnabled (true) 來重新啟用 Cookie 的使用方式。(Since v2.6.0) And if cookieCfg.enabled is also defined it will take precedence over these values, Cookie usage can be re-enabled after initialization via the core.getCookieMgr().setEnabled(true).
的別名 cookieCfg.enabledalias for cookieCfg.enabled
cookieDomaincookieDomain 自訂 cookie 網域。Custom cookie domain. 如果您想要在子域之間共用 Application Insights cookie,這會很有説明。This is helpful if you want to share Application Insights cookies across subdomains.
(因為 v 2.6.0) 如果 cookieCfg.domain 已定義,則會優先于此值。(Since v2.6.0) If cookieCfg.domain is defined it will take precedence over this value.
的別名 cookieCfg.domainalias for cookieCfg.domain
cookiePathcookiePath 自訂 cookie 路徑。Custom cookie path. 如果您想要在應用程式閘道後方共用 Application Insights cookie,這會很有説明。This is helpful if you want to share Application Insights cookies behind an application gateway.
如果 cookieCfg.path 已定義,則其優先順序會高於此值。If cookieCfg.path is defined it will take precedence over this value.
的別名 cookieCfg.pathalias for cookieCfg.path
(自 2.6.0) (Since 2.6.0)
isRetryDisabledisRetryDisabled 若為 false,則在206上重試 (部分成功) 、408 (timeout) 、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) booleanboolean
isStorageUseDisabledisStorageUseDisabled 若為 true,SDK 將不會儲存或讀取本機和會話儲存體中的任何資料。If true, the SDK will not store or read any data from local and session storage. booleanboolean
isBeaconApiDisabledisBeaconApiDisabled 若為 false,SDK 會使用指標API傳送所有遙測If false, the SDK will send all telemetry using the Beacon API booleanboolean
onunloadDisableBeacononunloadDisableBeacon 當索引標籤關閉時,SDK 會使用指標API來傳送所有剩餘的遙測When tab is closed, the SDK will send all remaining telemetry using the Beacon API booleanboolean
sdkExtensionsdkExtension 設定 sdk 延伸模組名稱。Sets the sdk extension name. 只允許字母字元。Only alphabetic characters are allowed. 延伸模組名稱會新增為 ' 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'). 字串string
isBrowserLink​TrackingEnabledisBrowserLink​TrackingEnabled 若為 true,SDK 將會追蹤所有 瀏覽器連結 要求。If true, the SDK will track all Browser Link requests. booleanboolean
appIdappId AppId 可用於在用戶端上發生的 AJAX 相依性與伺服器端要求之間的相互關聯。AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. 啟用指標 API 時,它無法自動使用,但可以在設定中手動設定。When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. 字串string
啟用​CorsCorrelationenable​CorsCorrelation 若為 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. booleanboolean
namePrefixnamePrefix 選擇性的值,將用作 localStorage 和 cookie 名稱的名稱後置詞。An optional value that will be used as name postfix for localStorage and cookie name. 字串string
啟用​AutoRoute​追蹤enable​AutoRoute​Tracking 自動追蹤單一頁面應用程式中的路由變更 (SPA) 。Automatically track route changes in Single Page Applications (SPA). 若為 true,每個路由變更都會將新的 Pageview 傳送至 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. booleanboolean
enableRequest​HeaderTrackingenableRequest​HeaderTracking 若為 true,則會追蹤 AJAX & Fetch 要求標頭。If true, AJAX & Fetch request headers is tracked. booleanboolean
enableResponse​HeaderTrackingenableResponse​HeaderTracking 若為 true,則會追蹤 AJAX & Fetch 要求的回應標頭。If true, AJAX & Fetch request's response headers is tracked. booleanboolean
distributedTracingModedistributedTracingMode 設定分散式追蹤模式。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. DistributedTracingModesDistributedTracingModesor
(自 v 2.6.0) DistributedTracingModes.AI_AND_W3C(Since v2.6.0) DistributedTracingModes.AI_AND_W3C
(v 2.5.11 或更早的) DistributedTracingModes.AI(v2.5.11 or earlier) DistributedTracingModes.AI
啟用​AjaxErrorStatusTextenable​AjaxErrorStatusText 若為 true,則在失敗 AJAX 要求的相依性事件中包含回應錯誤資料文字。If true, include response error data text in dependency event on failed AJAX requests. booleanboolean
啟用​AjaxPerfTrackingenable​AjaxPerfTracking 旗標,可讓您查閱和包含其他瀏覽器視窗。報告 (中的效能時間 ajax XHR 和提取) 回報的度量。Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics. booleanboolean
maxAjaxPerf​LookupAttemptsmaxAjaxPerf​LookupAttempts 要尋找視窗的最大次數。效能計時 ((如果有) 的話),因為並非所有的瀏覽器都填入視窗。在報告 XHR 要求結束之前的效能,以及提取要求之後,就會在完成之後加入。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. NUMERICnumeric
ajaxPerfLookupDelayajaxPerfLookupDelay 重新嘗試尋找 windows 之前要等候的時間量。要求的效能 ajax 時間,以毫秒為單位,並直接傳遞給 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(). NUMERICnumeric
25毫秒25 ms
enableUnhandled​PromiseRejection​追蹤enableUnhandled​PromiseRejection​Tracking 若為 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. booleanboolean
停用​InstrumentationKey​驗證disable​InstrumentationKey​Validation 若為 true,則會略過檢測金鑰驗證檢查。If true, instrumentation key validation check is bypassed. booleanboolean
enablePerfMgrenablePerfMgr 當啟用 (true 時) 這會為已檢測的程式碼建立本機 perfEvents,以透過 doPerf () helper) 發出 perfEvents (。When enabled (true) this will create local perfEvents for code that has been instrumented to emit perfEvents (via the doPerf() helper). 這可以用來根據您的使用方式,或在您自己的檢測程式碼內選擇性地識別 SDK 內的效能問題。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. 由於 v 2.5。7Since v2.5.7 booleanboolean
perfEvtsSendAllperfEvtsSendAll 當啟用 enablePerfMgr 時, IPerfManager 會引發 INotificationManager。 perfEvent () 此旗標會決定是否引發事件 (並傳送至所有事件的所有接聽程式) (true) ,或僅針對 ' parent ' 事件 (false < 預設 >) 。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>).
IPerfEvent 是在建立此事件時,沒有其他 IPerfEvent 仍在執行的事件,而且其 屬性不是 null 或未定義。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. 由於 v 2.5。7Since v2.5.7
idLengthidLength 識別用來產生新的隨機會話和使用者識別碼值的預設長度。Identifies the default length used to generate new random session and user id values. 預設值為22,先前的預設值為 5 (v 2.5.8 或更少) 。如果您需要保留先前的最大長度,則應該將此值設定為5。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. NUMERICnumeric

從版本2.6.0 中,cookie 管理現在可直接從實例使用,而且可以在初始化之後停用和重新啟用。From version 2.6.0, cookie management is now available directly from the instance and can be disabled and re-enabled after initialization.

如果透過或設定在初始化期間停用 disableCookiesUsage cookieCfg.enabled ,您現在可以透過 ICookieMgr setEnabled 函數重新啟用。If disabled during initialization via the disableCookiesUsage or cookieCfg.enabled configurations, you can now re-enable via the ICookieMgr setEnabled function.

以實例為基礎的 cookie 管理也會取代、和的先前 CoreUtils 全域函數 disableCookies() setCookie(...) getCookie(...) deleteCookie(...)The instance based cookie management also replaces the previous CoreUtils global functions of disableCookies(), setCookie(...), getCookie(...) and deleteCookie(...). 為了受益于版本2.6.0 中也引進的樹狀功能增強功能,您應該不會再使用全域功能。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.


在版本2.6.0 中新增以實例為基礎的 cookie 管理的 cookie 設定。Cookie Configuration for instance based cookie management added in version 2.6.0.

NameName 描述Description 類型和預設值Type and Default
已啟用enabled 布林值,指出目前的實例是否啟用 SDK 使用 cookie。A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance. 若為 false,此設定所初始化的 SDK 實例將不會儲存或讀取 cookie 中的任何資料If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies booleanboolean
網域domain 自訂 cookie 網域。Custom cookie domain. 如果您想要在子域之間共用 Application Insights cookie,這會很有説明。This is helpful if you want to share Application Insights cookies across subdomains. 如果未提供,會使用來自根 cookieDomain 值的值。If not provided uses the value from root cookieDomain value. 字串string
路徑path 指定要用於 cookie 的路徑(如果未提供,則會使用來自根值的任何值) cookiePathSpecifies the path to use for the cookie, if not provided it will use any value from the root cookiePath value. 字串string
System.windows.application.getcookiegetCookie 提取已命名 cookie 值的函式,如果未提供,則會使用內部 cookie 剖析/快取。Function to fetch the named cookie value, if not provided it will use the internal cookie parsing / caching. (name: string) => string
System.windows.application.setcookiesetCookie 函數,用來設定具有指定值的已命名 cookie,只有在新增或更新 cookie 時才會呼叫。Function to set the named cookie with the specified value, only called when adding or updating a cookie. (name: string, value: string) => void
delCookiedelCookie 用來刪除具有指定值之已命名 cookie 的函式(與 System.windows.application.setcookie 分隔),以避免需要剖析該值,以判斷是否要加入或移除 cookie。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. 如果未提供,則會使用內部 cookie 剖析/快取。If not provided it will use the internal cookie parsing / caching. (name: string, value: string) => void

啟用頁面追蹤時間Enable time-on-page tracking

藉由設定 autoTrackPageVisitTime: true ,會追蹤使用者花在每個頁面上的時間。By setting autoTrackPageVisitTime: true, the time a user spends on each page is tracked. 在每個新的 PageView 上,使用者花費在 上一頁 的持續時間會以名為的 自訂 計量來傳送 PageVisitTimeOn 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".

啟用相互關聯Enable Correlation

相互關聯會產生和傳送資料,以啟用分散式追蹤並提供 應用程式對應端對端交易視圖及其他診斷工具。Correlation generates and sends data that enables distributed tracing and powers the application map, end-to-end transaction view, and other diagnostic tools.

下列範例會顯示啟用相互關聯所需的所有可能設定,以及下列案例特定附注:The following example shows all possible configurations required to enable correlation, with scenario-specific notes below:

// excerpt of the config section of the JavaScript SDK snippet with correlation
// between client-side AJAX and server requests enabled.
cfg: { // Application Insights Configuration
    disableFetchTracking: false,
    enableCorsCorrelation: true,
    enableRequestHeaderTracking: true,
    enableResponseHeaderTracking: true,
    correlationHeaderExcludedDomains: ['myapp.azurewebsites.net', '*.queue.core.windows.net']
    /* ...Other Configuration Options... */

如果與用戶端通訊的任何協力廠商伺服器無法接受 Request-IdRequest-Context 標頭,而且您無法更新其設定,則您必須透過 configuration 屬性將它們放入排除清單中 correlationHeaderExcludeDomainsIf any of your third-party servers that the client communicates with cannot accept the Request-Id and Request-Context headers, and you cannot update their configuration, then you'll need to put them into an exclude list via the correlationHeaderExcludeDomains configuration property. 這個屬性支援萬用字元。This property supports wildcards.

伺服器端必須能夠接受與這些標頭存在的連接。The server-side needs to be able to accept connections with those headers present. 視伺服器端的設定而 Access-Control-Allow-Headers 定,通常必須以手動方式加入和來延伸伺服器端清單 Request-Id Request-ContextDepending on the Access-Control-Allow-Headers configuration on the server-side it is often necessary to extend the server-side list by manually adding Request-Id and Request-Context.

存取控制-允許-標頭: Request-IdRequest-Context<your header>Access-Control-Allow-Headers: Request-Id, Request-Context, <your header>


如果您使用的是 OpenTelemtry Application Insights 或2020或更新版本中發行的 Sdk,我們建議使用 WC3 TraceCoNtextIf you are using OpenTelemtry or Application Insights SDKs released in 2020 or later, we recommend using WC3 TraceContext. 請參閱 這裡的設定指引。See configuration guidance here.

單一頁面應用程式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.

目前,我們提供個別的 回應外掛程式,您可以使用此 SDK 進行初始化。Currently, we offer 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.


enableAutoRouteTracking: true只有當您 使用回應外掛程式時,才使用。Use enableAutoRouteTracking: true only if you are not using the React plugin. 兩者都能夠在路由變更時傳送新的 PageViews。Both are capable of sending new PageViews when the route changes. 如果兩者都啟用,可能會傳送重複的 PageViews。If both are enabled, duplicate PageViews may be sent.


React Native (英文)React Native
按一下 [分析自動收集]Click Analytics Auto-collection

探索瀏覽器/用戶端資料Explore browser/client-side data

瀏覽器/用戶端資料可透過進入 計量 ,並新增您感興趣的個別計量來查看:Browser/client-side data can be viewed by going to Metrics and adding individual metrics you are interested in:

Application Insights 中 [計量] 頁面的螢幕擷取畫面,其中顯示 web 應用程式的度量資料圖形顯示。

您也可以透過入口網站中的瀏覽器體驗,從 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.

Application Insights 中瀏覽器頁面的螢幕擷取畫面,其中顯示如何將瀏覽器失敗或瀏覽器效能新增至您可以針對 web 應用程式查看的度量。


Application Insights 中 [效能] 頁面的螢幕擷取畫面,其中顯示 web 應用程式的作業計量圖形顯示。


Application Insights 中 [效能] 頁面的螢幕擷取畫面,其中顯示 web 應用程式的相依性計量圖形顯示。


若要查詢 JavaScript SDK 所收集的遙測,請選取 [ 在記錄中查看 (分析]) 按鈕。To query your telemetry collected by the JavaScript SDK, select the View in Logs (Analytics) button. 藉由加入的 where 語句 client_Type == "Browser" ,您將只會看到來自 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 入口網站中 unminified 例外狀況遙測的縮減呼叫堆疊。The minified callstack of your exception telemetry can be unminified in the Azure portal. [例外狀況詳細資料] 面板上的所有現有整合都可使用新 unminified 的呼叫堆疊。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 入口網站  的動畫影像中,顯示如何從組建資料夾將來源對應檔案拖放到 Azure 入口網站的 [呼叫堆疊] 視窗中。Drag and drop the source maps onto the call stack in the Azure portal An animated image showing how to drag and drop source map files from a build folder into the Call Stack window in the Azure portal.

Application Insights Web 基本Application Insights Web Basic

針對輕量體驗,您可以改為安裝 Application Insights 的基本版本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 number of features and functionalities and relies on you to build it up as you see fit. 例如,它不會執行任何 autocollection (無法攔截的例外狀況、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.operationcontext.telemetryTraceMoved context.operation to context.telemetryTrace. 某些欄位也會 (operation.id --> telemetryTrace.traceID) 變更。Some fields were also changed (operation.id --> telemetryTrace.traceID).
    • 若要手動重新整理目前的 pageview 識別碼 (例如,在 SPA 應用程式) 中,請使用 appInsights.properties.context.telemetryTrace.traceID = Microsoft.ApplicationInsights.Telemetry.Util.generateW3CId()To manually refresh the current pageview ID (for example, in SPA apps), use appInsights.properties.context.telemetryTrace.traceID = Microsoft.ApplicationInsights.Telemetry.Util.generateW3CId().


      若要讓追蹤識別碼成為唯一的,您先前使用的是 Util.newId() ,現在請使用 Util.generateW3CId()To keep the trace ID unique, where you previously used Util.newId(), now use Util.generateW3CId(). 最後最後是作業識別碼。Both ultimately end up being the operation ID.

如果您使用目前的 application insights 生產 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://js.monitor.azure.com/scripts/b/ai.2.min.jss"

在內部環境中測試,以確認監視遙測如預期般運作。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

只有 36 KB 的 gzipped,而且只需要約15毫秒來初始化,Application Insights 在您的網站中新增了可忽略的 loadtime 量。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 + & 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.

如需最新的更新和錯誤修正, 請參閱版本資訊。For the latest updates and bug fixes consult the release notes.

後續步驟Next steps