### Module Loader Setup and Test Execution Source: https://github.com/microsoft/applicationinsights-js/blob/main/tools/applicationinsights-web-snippet/Tests/UnitTests.html Initializes the module loader with specific paths for QUnit and fetch, adds necessary modules, and configures the test module to run tests after QUnit starts. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); modules.add("qunit"); modules.add("@microsoft/ai-test-framework"); var testModule = modules.add("Tests/Unit/src/snippet.tests", "./Unit/dist/applicationinsights-web-snippet.tests.js") testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); ``` -------------------------------- ### Basic SDK Setup Source: https://github.com/microsoft/applicationinsights-js/blob/main/shared/1ds-core-js/README.md Demonstrates the basic setup and initialization of the AppInsightsCore with a configuration object. ```javascript import { AppInsightsCore, IExtendedConfiguration } from '@microsoft/1ds-core-js'; ``` ```javascript var appInsightsCore: AppInsightsCore = new AppInsightsCore(); var coreConfig: IExtendedConfiguration = { instrumentationKey: "YOUR_TENANT_KEY" }; //Initialize SDK appInsightsCore.initialize(coreConfig, []); ``` -------------------------------- ### Install OS Plugin and Web SDK Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-osplugin-js/README.md Install the necessary npm packages for the OS plugin and the Application Insights Web SDK. ```bash npm install --save @microsoft/applicationinsights-osplugin-js @microsoft/applicationinsights-web ``` -------------------------------- ### Install Dependencies Source: https://github.com/microsoft/applicationinsights-js/blob/main/CONTRIBUTING.md Install project dependencies and the global Rush package manager. ```bash npm install npm install -g @microsoft/rush ``` -------------------------------- ### Module Loader and Test Setup Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-perfmarkmeasure-js/Tests/UnitTests.html Initializes the ModuleLoader with specific paths for QUnit and fetch, then loads common modules and the main test module. This setup is required before running the tests. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); // Load qunit here instead of with tests, otherwise will not work modules.add("qunit"); loadFetchModule(modules, "whatwg-fetch"); loadCommonModules(modules, function() { var testModule = modules.add("Tests/Unit/src/appinsights-perfmarkmeasure.tests", "./Unit/dist/appinsights-perfmarkmeasure.tests.js") testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### Install Tee Channel and Web SDK Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/tee-channel-js/README.md Install the necessary npm packages for the Tee Channel and the core Application Insights Web SDK. ```bash npm install --save @microsoft/applicationinsights-teechannel-js @microsoft/applicationinsights-web ``` -------------------------------- ### PerfMarkMeasureManager Configuration Example Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-perfmarkmeasure-js/README.md Demonstrates how to instantiate and configure the PerfMarkMeasureManager with custom prefixes, name mappings, and options for using marks and measures. This setup allows for fine-grained control over performance event tracking. ```typescript import { doPerf } from '@microsoft/applicationinsights-core-js'; import { PerfMarkMeasureManager } from '@microsoft/applicationinsights-perfmarkmeasure-js'; const perfManager = new PerfMarkMeasureManager({ useMarks: true, useEndMarks: true, markPrefix: "tst.mark.", markEndPrefix: "tst.markend.", measurePrefix: "tst.measure.", markNameMap: { "test": "mapped1", "test3": "mapped3" }, measureNameMap: { "test": "measure1", "test2": "measure2" } }); doPerf(manager, () => "test", (perfEvent) => { // A mark has been added to window.performance called 'tst.mark.test' }); // Another mark has been added to window.performance called 'tst.markend.test' // And a measure will also exist in window.performance called 'tst.measure.test' ``` -------------------------------- ### RequireJS Module Loading Example Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md Example of how to load an Application Insights module using require() when it's not immediately initialized. ```javascript var aiSdk = require("@microsoft/applicationinsights-web"); ``` -------------------------------- ### NPM Install Nightly Build Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md Install nightly builds from the NPM registry using the 'nightly' tag or a specific nightly version number. ```bash npm install @microsoft/applicationinsights-web@nightly ``` ```bash npm install @microsoft/applicationinsights-web@2.7.3-nightly.2112-08 ``` -------------------------------- ### Install Application Insights Web SDK and CfgSync Plugin Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-cfgsync-js/README.md Install the necessary packages for the Application Insights Web SDK and the CfgSync plugin using npm. ```sh npm install @microsoft/applicationinsights-web @microsoft/applicationinsights-cfgsync-js ``` -------------------------------- ### Build Application Insights JavaScript SDK Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/applicationinsights-channel-js/README.md Installs dependencies and builds the SDK. Run this command in your project directory. ```bash npm install -g grunt-cli npm install npm run build --silent ``` -------------------------------- ### Install Performance Mark and Measure Plugin Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-perfmarkmeasure-js/README.md Install the necessary npm packages for the Application Insights web SDK and the performance mark and measure plugin. ```bash npm install --save @microsoft/applicationinsights-perfmarkmeasure-js @microsoft/applicationinsights-web ``` -------------------------------- ### Trace Host Example Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/withSpan.md Instantiating a trace host, which can be an AppInsightsCore or AISKU instance. ```typescript const core = new AppInsightsCore(); // or const appInsights = new ApplicationInsights({ ... }); ``` -------------------------------- ### Configure Dependencies Plugin Extension Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md Initialize extension configurations under the specific extension, such as the DependenciesPlugin. This example shows how to configure ignored headers for the DependenciesPlugin. ```js const appInsights = new ApplicationInsights({ config: { connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', extensionConfig: { [DependenciesPlugin.identifier]: { ignoreHeaders: [] } } } }); ``` -------------------------------- ### Test Module Loading and Execution Source: https://github.com/microsoft/applicationinsights-js/blob/main/AISKU/Tests/UnitTests.html Loads the main test module and configures its execution. Starts QUnit and runs the tests defined within the module. ```javascript loadCommonModules(modules, function () { var testModule = modules.add("Tests/Unit/src/aiskuunittests", "./Unit/dist/aiskuunittests.tests.js") testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### NPM Setup and Basic Usage of Offline Channel Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/offline-channel-js/README.md Demonstrates how to set up the offline channel using NPM, configure it with storage providers and minimum persistence level, and manage online/offline states to track events. ```javascript import { OfflineChannel, eStorageProviders } from "@microsoft/applicationinsights-offlinechannel-js"; let offlineChannel = new OfflineChannel(); let coreConfig = { connectionString: "YOUR_CONNECTION_STRING", extensionConfig: { [offlineChannel.identifier]: { providers: [eStorageProviders.LocalStorage, eStorageProviders.IndexedDb], minPersistenceLevel: 2, // only events with PersistenceLevel >=2 will be saved/sent } // Add config for offline support channel } }; let appInsights = new ApplicationInsights({config: coreConfig}); appInsights.loadAppInsights(); // this is to make sure offline channel is initialized after sender channel appInsights.addPlugin(offlineChannel); // get offlineListener to set online/offline status let offlineListener = offlineChannel.getOfflineListener(); // set application status to online offlineListener.setOnlineState(1); // offline channel will not process events when the status is online appInsights.track({ name:"onlineEvent" }); // sender channel will send this event // set application status to offline offlineListener.setOnlineState(2); // offline channel will process and save this event to the configured persistent storage // the event will be sent when the application status is online again appInsights.track({ name:"offlineEvent" }); ``` -------------------------------- ### Module Loader and Test Setup Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/tee-channel-js/Tests/UnitTests.html Initializes the module loader with paths to QUnit, Sinon, and fetch, then loads common modules and the specific teechannel tests. This sets up the testing environment. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", sinon: "../../common/Tests/External/sinon-7.3.1", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); // Load qunit here instead of with tests, otherwise will not work modules.add("qunit"); modules.add("sinon"); loadFetchModule(modules, "whatwg-fetch"); loadCommonModules(modules, function() { var testModule = modules.add("Tests/Unit/src/teechannel.tests", "./Unit/dist/teechannel.tests.js"); testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### Add Manual Test Scenario in span-e2e-manual-test.html Source: https://github.com/microsoft/applicationinsights-js/blob/main/AISKU/Tests/Manual/README.md Example of how to define and execute a manual E2E test scenario directly in an HTML file using the Application Insights SDK. This involves starting a span with specific attributes, setting its status, and flushing. ```javascript function testYourScenario() { if (!appInsights) return; const span = appInsights.startSpan('E2E-Manual-YourScenario', { kind: 1, // CLIENT attributes: { 'test.scenario': 'your-scenario', 'custom.property': 'value' } }); if (span) { span.setStatus({ code: 1 }); span.end(); log('✅ Your scenario sent', 'success'); } appInsights.flush(); } ``` -------------------------------- ### Add E2E Test Scenario in SpanE2E.Tests.ts Source: https://github.com/microsoft/applicationinsights-js/blob/main/AISKU/Tests/Manual/README.md Example of how to define a new E2E test scenario using the Application Insights SDK within a TypeScript test file. Ensure to start a span, set its status, and end it, followed by flushing telemetry. ```typescript this.testCase({ name: "E2E: Your new scenario", test: () => { const span = this._ai.startSpan("E2E-YourScenario", { kind: eOTelSpanKind.CLIENT, attributes: { "test.scenario": "your-scenario", "custom.property": "value" } }); if (span) { span.setStatus({ code: eOTelSpanStatusCode.OK }); span.end(); } this._ai.flush(); Assert.ok(span, "Span created"); } }); ``` -------------------------------- ### Custom Start Times for Spans Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/startActiveSpan.md Enables setting a custom start time for a span using the `startTime` option. This is useful for backfilling telemetry or accurately representing operations that started in the past. ```typescript startActiveSpan( appInsights, 'delayed-operation', { startTime: performance.now() - 1000 // Started 1 second ago }, (scope) => { scope.span.setAttribute('delayed', true); return processData(); } ); ``` -------------------------------- ### Initialize and Run Unit Tests Source: https://github.com/microsoft/applicationinsights-js/blob/main/tools/shims/Tests/UnitTests.html Sets up the module loader, loads necessary test modules including shims, and initiates the QUnit test runner. This is the main entry point for executing the unit tests. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); modules.add("qunit"); loadCommonModules(modules, function() { var testModule = modules.add("Tests/Unit/src/shims.tests", "./Unit/dist/shimstests.js"); testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### Initialize Module Loader and Run Tests Source: https://github.com/microsoft/applicationinsights-js/blob/main/shared/1ds-core-js/test/UnitTests.html Loads necessary modules including QUnit, pako, and whatwg-fetch, then initializes and runs the core unit tests. Ensure QUnit is loaded before tests to prevent issues. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.0.0", "sinon": "../../common/Tests/External/sinon-7.3.1", "pako": "./node_modules/pako/dist/pako" } }); // Load qunit here instead of with tests, otherwise will not work modules.add("qunit"); modules.add("pako"); loadFetchModule(modules, "whatwg-fetch"); loadCommonModules(modules, () => { var testModule = modules.add("core.unittests", "./Unit/dist/core.unittests.js") testModule.run = function () { console && console.log("Starting tests..."); QUnit.start(); }; modules.run(); }); ``` -------------------------------- ### Install Application Insights and Debug Plugin Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-debugplugin-js/README.md Install the necessary packages for Application Insights and the debug plugin using npm. ```zsh npm install --save @microsoft/applicationinsights-debugplugin-js @microsoft/applicationinsights-web ``` -------------------------------- ### Module Loader and Test Setup Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/applicationinsights-channel-js/Tests/UnitTests.html Initializes the module loader with paths to testing dependencies like QUnit and Sinon. It then loads the necessary modules and prepares for test execution. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", sinon: "../../common/Tests/External/sinon-7.3.1", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); // Load qunit here instead of with tests, otherwise will not work modules.add("qunit"); modules.add("sinon"); loadFetchModule(modules, "whatwg-fetch"); loadCommonModules(modules, function() { var testModule = modules.add("Tests/Unit/src/aichannel.tests", "./Unit/dist/aichannel.tests.js"); testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### Initialize Application Insights SDK with URL and Options Source: https://github.com/microsoft/applicationinsights-js/blob/main/AISKU/Tests/Manual/HelloWorld.html This example demonstrates initializing the Application Insights SDK using a specific URL for the SDK script and enabling CORS correlation. It's suitable for scenarios where you need to load the SDK from a custom location or enable specific cross-origin tracking features. ```javascript var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.8.0.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var s="Track"+r[0];if(n("start"+s),n("stop"+s),n("addTelemetryInitializer"),n("setAuthenticatedUserContext"),n("clearAuthenticatedUserContext"),n("flush"),t.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("\_"+(r="onerror"));var o=a[r];a[r]=function(e,n,i,a,s){var c=o&&o(e,n,i,a,s);return!0!==c&&t["\_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:s}),c},e.autoExceptionInstrumented=!0}return t}( // { // url: "./ai.2.8.0.js", // instrumentationKey: "2bd72339-a683-4cce-8ed7-b1b0e8767295", // enableCorsCorrelation: true, // enableApplicationInsightsTrace: true // } // ); window[aiName] = aisdk; ``` -------------------------------- ### Build and Test Project Source: https://github.com/microsoft/applicationinsights-js/blob/main/CONTRIBUTING.md Build all packages in the project and run all tests. ```bash rush build npm run test ``` -------------------------------- ### Initialize Application Insights SDK v2 with Connection String (NPM) Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/upgrade/v2_UpgradeGuide.md For NPM installations, use the `downloadAndSetup` function to load the full Application Insights script from the CDN and initialize it with your connection string. ```typescript appInsights.downloadAndSetup({ connectionString: "InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx", url: "https://js.monitor.azure.com/scripts/b/ai.2.min.js" }); ``` -------------------------------- ### Basic NPM Setup for Application Insights Dependencies Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-dependencies-js/README.md Demonstrates how to set up Application Insights with the Dependencies Plugin using NPM. Ensure you replace 'YOUR_INSTRUMENTATION_KEY_GOES_HERE' with your actual key. The plugin is configured to ignore specific headers. ```javascript import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { AjaxPlugin } from '@microsoft/applicationinsights-dependencies-js'; const dependencyPlugin = new AjaxPlugin(); const appInsights = new ApplicationInsights({ config: { connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', extensions: [dependencyPlugin], extensionConfig: { [dependencyPlugin.identifier]: { ignoreHeaders:[ "Authorization", "X-API-Key", "WWW-Authenticate" ] } } } }); appInsights.loadAppInsights(); appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview ``` -------------------------------- ### Stop Page Tracking Source: https://github.com/microsoft/applicationinsights-js/blob/main/AISKU/API.md Use stopTrackPage to end the page view timer started by startTrackPage and send the telemetry. It logs the duration between start and stop calls. ```typescript stopTrackPage(name?: string, url?: string, customProperties?: { [name: string]: any; }); ``` -------------------------------- ### startActiveSpan with Span Options Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/startActiveSpan.md Example demonstrating the use of startActiveSpan with optional configurations, including span kind and attributes. This allows for richer span data, such as HTTP method and URL. ```typescript startActiveSpan(appInsights, 'api-call', { kind: OTelSpanKind.CLIENT, attributes: { 'http.method': 'GET', 'http.url': '/api/data' } }, (scope) => { // Work here } ); ``` -------------------------------- ### Install Application Insights SDK via NPM Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md Use this command to install the Application Insights JavaScript SDK package using npm. Typings are included. ```sh npm i --save @microsoft/applicationinsights-web ``` -------------------------------- ### Install Application Insights Web Snippet Source: https://github.com/microsoft/applicationinsights-js/blob/main/tools/applicationinsights-web-snippet/README.md Install the Application Insights Web Snippet package using npm. This is the first step to include the SDK in your project. ```bash npm i @microsoft/applicationinsights-web-snippet ``` -------------------------------- ### Basic useSpan Example with Application Insights Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/useSpan.md Demonstrates basic usage of `useSpan` to execute code with a span as the active context. Requires Application Insights and core SDK initialization. ```typescript import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { useSpan } from '@microsoft/applicationinsights-core-js'; const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING' } }); appInsights.loadAppInsights(); const tracer = appInsights.trace.getTracer('my-service'); // Create a span const span = tracer.startSpan('operation'); // Execute code with span as active context const result = useSpan(appInsights, span, (scope) => { span.setAttribute('step', 'processing'); // Perform work - span is active during execution const data = processData(); span.setAttribute('result', 'success'); return data; }); span.end(); ``` -------------------------------- ### Install Application Insights Web SDK Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/README.md Install the Application Insights web SDK package using npm. This package includes the OpenTelemetry-compatible tracing APIs. ```bash npm install @microsoft/applicationinsights-web ``` -------------------------------- ### startActiveSpan Usage with AISKU Instance Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/startActiveSpan.md Example showing how to use the startActiveSpan helper function with an ApplicationInsights instance (AISKU). This is suitable for direct instrumentation within an application context. ```typescript import { startActiveSpan } from '@microsoft/applicationinsights-core-js'; // Using with AISKU instance startActiveSpan(appInsights, 'operation-name', (scope) => { // Work here }); ``` -------------------------------- ### Example Usage of stopTrackEvent Source: https://github.com/microsoft/applicationinsights-js/blob/main/RELEASES.md This example demonstrates how to use the `stopTrackEvent` function, which requires property values to be strings. It addresses an issue where non-string values could cause errors. ```typescript stopTrackEvent({ eventName: "myEvent", properties: { prop1: "value1", prop2: "value2" } }); ``` -------------------------------- ### Get Tracer Instance Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/traceApi.md Shows how to get a tracer instance using the Trace API. Tracers are cached by name and version, ensuring that multiple calls with the same parameters return the same instance. ```typescript const trace = otelApi.trace; // Get a tracer with just a name const tracer1 = trace.getTracer('my-service'); // Get a tracer with name and version (optional) const tracer2 = trace.getTracer('user-service', '2.1.0'); // Get a tracer with options const tracer3 = trace.getTracer('payment-service', '1.5.0', { schemaUrl: 'https://example.com/schema/v1' }); // Subsequent call returns cached instance const tracer4 = trace.getTracer('user-service', '2.1.0'); console.log(tracer2 === tracer4); // true ``` -------------------------------- ### Initialize Application Insights with NPM Setup Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md This JavaScript code demonstrates how to initialize Application Insights using the NPM package. Remember to replace 'YOUR_CONNECTION_STRING_GOES_HERE' with your actual connection string. Manually call trackPageView to establish the current user/session/pageview. ```js import { ApplicationInsights } from '@microsoft/applicationinsights-web' const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE' /* ...Other Configuration Options... */ } }); appInsights.loadAppInsights(); appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview ``` -------------------------------- ### Initializing Application Insights and Accessing OTel API Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/otelApi.md Demonstrates the basic setup for Application Insights Web SDK and how to retrieve the OTel API instance. It logs the availability of different API components. ```typescript import { ApplicationInsights } from '@microsoft/applicationinsights-web'; const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING', traceCfg: { suppressTracing: false } } }); appInsights.loadAppInsights(); // Get the OTel API const otelApi = appInsights.otelApi; // Access different parts of the API console.log('Has trace API:', !!otelApi.trace); console.log('Has host:', !!otelApi.host); console.log('Configuration available:', !!otelApi.cfg); ``` -------------------------------- ### Install Application Insights Click Analytics JS via NPM Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-clickanalytics-js/README.md Install the necessary npm packages for Application Insights and Click Analytics. This is the recommended approach for most modern web applications. ```bash npm install --save @microsoft/applicationinsights-clickanalytics-js @microsoft/applicationinsights-web ``` -------------------------------- ### NPM Setup for Application Insights with Debug Plugin Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-debugplugin-js/README.md Configure Application Insights with the Debug Plugin using npm. This setup allows for detailed tracking of various Application Insights functions. ```javascript import { Application Insights } from '@microsoft/applicationinsights-web'; import { DebugPlugin } from '@microsoft/applicationinsights-debugplugin-js'; const toTrack = [ 'trackEvent', 'trackPageView', 'trackPageViewPerformance', 'trackException', 'trackTrace', 'trackMetric', 'trackDependencyData', 'throwInternal', // called when a message is logged internally 'logInternalMessage', // called when a message is logged internally 'triggerSend', // called when data is queued to be sent to the server '_sender', // called when data is sent to the server ]; const debugPluginInstance = new DebugPlugin(); const appInsights = new ApplicationInsights({ config: { connectionString: 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY_GOES_HERE', extensions: [debugPluginInstance], extensionConfig: { [DebugPlugin.identifier]: { trackers: toTrack } } } }); appInsights.loadAppInsights(); appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview ``` -------------------------------- ### Start Page View Tracking Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/API-reference.md Initiates a timer for measuring page load duration. Call this when you want to manually control the start of the page view timing. Telemetry is not sent until stopTrackPage is called. ```typescript startTrackPage(name?: string) ``` -------------------------------- ### ModuleLoader Configuration and Test Execution Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-properties-js/Tests/UnitTests.html This snippet shows the setup for running unit tests using ModuleLoader. It configures paths for QUnit and fetch, loads necessary modules, and defines how to run the tests. ```javascript var modules = new ModuleLoader({ baseUrl: '../', paths: { qunit: "../../common/Tests/External/qunit-2.9.3", "whatwg-fetch": "../../common/Tests/External/whatwg-fetch.3.6.2" } }); // Load qunit here instead of with tests, otherwise will not work modules.add("qunit"); modules.add("pako","./node_modules/pako/dist/pako"); loadFetchModule(modules, "whatwg-fetch"); loadCommonModules(modules, function() { var testModule = modules.add("Tests/Unit/src/prop.tests", "./Unit/dist/prop.tests.js") testModule.run = function (tests) { console && console.log("Starting tests"); QUnit.start(); tests.runTests(); }; modules.run(); }); ``` -------------------------------- ### Install Application Insights Web Basic Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md Install the lightweight version of Application Insights using npm. This version includes minimal features and requires manual implementation for auto-collection and specific telemetry tracking. ```bash npm i --save @microsoft/applicationinsights-web-basic ``` -------------------------------- ### startTrackPage Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/API-reference.md Starts a timer for tracking page load time. Use this method when you need to manually control the start of the page view timer, without calculating the duration yourself. The actual telemetry is sent when `stopTrackPage` is called. ```APIDOC ## startTrackPage ### Description Starts the timer for tracking a page load time. This method is useful when you want to manually control the start of the page view timer. The duration will be calculated automatically when `stopTrackPage` is called. ### Method ```ts startTrackPage(name?: string) ``` ### Parameters #### Query Parameters - **name** (string) - Optional - The name used to identify the page in the portal. Defaults to the document title. ``` -------------------------------- ### Initialize Application Insights with Tee Channel Source: https://github.com/microsoft/applicationinsights-js/blob/main/channels/tee-channel-js/README.md Configure and load Application Insights with the Tee Channel extension. This example shows how to pass the tee channel via extensions and configure its specific settings. ```javascript import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { TeeChannel } from '@microsoft/applicationinsights-teechannel-js'; const teeChannel = new TeeChannel(); // TeeChannel configuration const teeChannelConfig = { teeChannels: [[]], ignoreCoreChannels: false }; // Application Insights Configuration passing the tee Channel via extensions const configObj = { instrumentationKey: "YOUR INSTRUMENTATION KEY", extensions: [teeChannel], extensionConfig: { [teeChannel.identifier]: teeChannelConfig }, }; const appInsights = new ApplicationInsights({ config: configObj }); appInsights.loadAppInsights(); ``` -------------------------------- ### Install Application Insights Core JS SDK Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/OTel/README.md Install the Application Insights core JS package using npm. This is a minimal option that includes tracing APIs but requires manual initialization of a trace provider. ```bash npm install @microsoft/applicationinsights-core-js ``` -------------------------------- ### Configure Application Insights with Connection String (NPM) Source: https://github.com/microsoft/applicationinsights-js/blob/main/README.md This example shows how to configure Application Insights using a connection string when integrating via NPM. Ensure you import the `ApplicationInsights` class and call `loadAppInsights()` to initialize the SDK. ```javascript import { ApplicationInsights } from '@microsoft/applicationinsights-web' const appInsights = new ApplicationInsights({ config: { connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE' /* ...Other Configuration Options... */ } }); appInsights.loadAppInsights(); appInsights.trackPageView(); ``` -------------------------------- ### CDN Setup for Application Insights with Debug Plugin Source: https://github.com/microsoft/applicationinsights-js/blob/main/extensions/applicationinsights-debugplugin-js/README.md Configure Application Insights with the Debug Plugin using a CDN. This setup allows for detailed tracking of various Application Insights functions via script tags. ```html ``` -------------------------------- ### Minimal SDK Configuration with Connection String Source: https://github.com/microsoft/applicationinsights-js/blob/main/docs/SdkLoadFailureSteps.md Use this minimal configuration to check for SDK initialization errors caused by incorrect or missing configuration. It isolates the connection string as the primary setting. ```javascript src: "https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js", cfg:{ connectionString: "YOUR_CONNECTION_STRING" }}); ```