[BUG] window.appInsights is `undefined`
See original GitHub issueEdit
So apparantly this isn’t a bug, but it’s still very confusing since it doesn’t work the way that’s described in the deocumentation. The documentation needs to be updated to mention that the npm version doesn’t populate window.appInsights, so it needs to be exported to be used in other components. See this comment below for an example: https://github.com/microsoft/ApplicationInsights-JS/issues/1951#issuecomment-1329154828
Original description
Description/Screenshot
window.appInsights is undefined, so I’m unable to use any appInsights methods in other files than the one where I declared appInsights. I’m using Svelte if that matters, and appInsights is initialized in App.svelte
in vscode:
in google chrome:
code:
const appInsights = new ApplicationInsights({
config: {
connectionString:
process.env.AZURE_APPLICATION_INNSIGHTS_CONNECTION_STRING,
},
});
appInsights.loadAppInsights();
appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview
window.appInsights.trackEvent('Test');
error messages:
Property ‘appInsights’ does not exist on type ‘Window & typeof globalThis’.ts(2339)
App.svelte:29 Uncaught TypeError: Cannot read properties of undefined (reading ‘trackEvent’) at instance (App.svelte:29:24) at init (index.mjs:1997:11) at new App (App.svelte:45:40) at main.js:3:13 at main.js:5:2
Steps to Reproduce
- OS/Browser: Windows 10 / Chrome Version 107.0.5304.107 (Official Build) (64-bit)
- SDK Version [e.g. 22]: 2.8.9
- How you initialized the SDK: npm-based
Expected behavior window.appInsights is NOT undefined
Additional context Add any other context about the problem here.
Issue Analytics
- State:
- Created 10 months ago
- Comments:11 (5 by maintainers)
Top GitHub Comments
@Snailedlt
for many website structures,
process.env
can’t be referenced directly inindex.html
, for example, if you are using React, you have to use env variables like this: connectionString: `%REACT_APP_CONNECTION_STRING%`. so using env variables in correct ways might help.I ended up just exporting appInsights like so:
And then loading it in App.svelte
And finally using it in any other file by importing it: