{"id":25638373,"url":"https://github.com/mindscapehq/raygun4js","last_synced_at":"2025-04-14T08:56:07.569Z","repository":{"id":38428087,"uuid":"8280065","full_name":"MindscapeHQ/raygun4js","owner":"MindscapeHQ","description":"JavaScript provider for Raygun","archived":false,"fork":false,"pushed_at":"2025-03-27T12:44:23.000Z","size":5360,"stargazers_count":151,"open_issues_count":26,"forks_count":60,"subscribers_count":25,"default_branch":"master","last_synced_at":"2025-04-07T01:12:04.452Z","etag":null,"topics":["breadcrumbs","error-handler","javascript","raygun","raygun4js","real-user-monitoring","sourcemaps","stack-traces","unhandled-errors","user-tracking"],"latest_commit_sha":null,"homepage":"https://raygun.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MindscapeHQ.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-02-19T00:15:50.000Z","updated_at":"2025-03-25T03:37:53.000Z","dependencies_parsed_at":"2024-04-17T02:52:42.560Z","dependency_job_id":"7ea25740-d728-460b-8e2f-a195f5b29c1c","html_url":"https://github.com/MindscapeHQ/raygun4js","commit_stats":{"total_commits":1214,"total_committers":66,"mean_commits":"18.393939393939394","dds":0.6845140032948929,"last_synced_commit":"d2a269c056a04439b4f24a37bfc38a68ebac58c9"},"previous_names":[],"tags_count":144,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MindscapeHQ%2Fraygun4js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MindscapeHQ%2Fraygun4js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MindscapeHQ%2Fraygun4js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MindscapeHQ%2Fraygun4js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MindscapeHQ","download_url":"https://codeload.github.com/MindscapeHQ/raygun4js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248852112,"owners_count":21171839,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["breadcrumbs","error-handler","javascript","raygun","raygun4js","real-user-monitoring","sourcemaps","stack-traces","unhandled-errors","user-tracking"],"created_at":"2025-02-23T02:25:35.872Z","updated_at":"2025-04-14T08:56:07.541Z","avatar_url":"https://github.com/MindscapeHQ.png","language":"JavaScript","readme":"# Raygun4js\n\n[Raygun.com][rayguncom] provider for client-side JavaScript\n\n[rayguncom]: https://raygun.com\n\n## Getting Started\n\n### Asynchronous method - Highly recommended\n\n**Step 1**\n\nNo installation via a package manager is required. Just add the following snippet to the beginning of the `\u003chead\u003e` tag within your markup. Please include this snippet before any other `\u003cscript\u003e` tag references are made to ensure that Raygun has the best chance to capture all error events on the page.\n\n```javascript\n\u003cscript type=\"text/javascript\"\u003e\n    !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){\n    (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],\n    f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){\n    h\u0026\u0026h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({\n    e:g})}}(window,document,\"script\",\"//cdn.raygun.io/raygun4js/raygun.min.js\",\"rg4js\");\n\u003c/script\u003e\n```\n\nThe above snippet will fetch the Raygun4JS script from our CDN asynchronously, so it doesn't block other scripts from being loaded. It will also catch errors that are thrown while the page is loading, and send them when the script is ready.\n\n\n**Note:** If you encounter a situation where no events are appearing within Raygun, you may need to hard code the URL protocol so that the CDN matches your hosting environment. This could look like one of the following -\n- `https://cdn.raygun.io/raygun4js/raygun.min.js` \n- `http://cdn.raygun.io/raygun4js/raygun.min.js` \n\nThis will be in replacement of `//cdn.raygun.io/raygun4js/raygun.min.js`.\n\n### Via package manager installation \nFor installations and usage via a package manager, refer to the [Synchronous methods](#synchronous-methods) section of this document.\n\n**Step 2**\n\nAdd the following lines to your JS site code and paste in your API key (from your Raygun Application Settings), to set up the provider to automatically send errors to your Raygun app:\n\n```javascript\n\u003cscript type=\"text/javascript\"\u003e\n    rg4js('apiKey', 'paste_your_api_key_here');\n    rg4js('enableCrashReporting', true);\n\u003c/script\u003e\n```\n\nThis will configure the provider to send to your Raygun app, and to automatically send all unhandled errors.\n\nThat's it for the basic setup! See **Usage** below for more info on how to send errors.\n\n**Snippet without page load error handler**\n\nIf you do not want errors to be caught while the page is loading, [use this snippet here][nohandler].\n\n[nohandler]: https://raw.github.com/MindscapeHQ/raygun4js/master/src/snippet/minified.nohandler.js\n\n### Synchronous methods\n\nNote that using these methods will not catch errors thrown while the page is loading. The script needs to be referenced before your other site/app scripts and will block the page load while it is being downloaded/parsed/executed.\n\nThis will also disrupt RUM timings, making them erroneous. For RUM, it is especially important that the async snippet method above is used, instead of one of the following.\n\n#### With Bower\n\nRun `bower install raygun4js`\n\n#### With NPM\n\n```javascript\nnpm install raygun4js --save\n```\n\nThis lets you require the library with tools such as Webpack or Browserify.\n\n#### From NuGet\n\nVisual Studio users can get it by opening the Package Manager Console and typing `Install-Package raygun4js`\n\n#### React Native/as a UMD module\n\nReact Native and other bundled app frameworks that use packaging/module loading libraries can use Raygun4JS as a UMD module:\n\n```\n// Install the library\n\nnpm install raygun4js --save\n\n// In a central module, reference and install the library\n\nimport rg4js from 'raygun4js'; // Import the library with this syntax\nvar rg4js = require('raygun4js'); // Or this syntax\n\nrg4js('enableCrashReporting', true);\nrg4js('apiKey', 'paste_your_api_key_here');\n// Any other config options you want such as rg4js('setUser', ...) [see below]\nrg4js('boot'); // For React Native only: add this after all other config options have been called\n```\n\nAll unhandled errors will then be sent to Raygun. You can also `require('raygun4js')` in any other modules and use the rest of the V2 API below - including `rg4js('send', error)` for manual error sending.\n\nIf you use this approach, we appreciate your feedback as this is a new feature for the library.\n\n#### Manual download\n\nDownload the [production version][min] or the [development version][max]. You can also download a version without\nthe jQuery hooks if you are not using jQuery or you wish to provide your own hooks. Get this as a\n[production version][min.vanilla] or [development version][max.vanilla].\n\n[min]: https://cdn.raygun.io/raygun4js/raygun.min.js\n[max]: https://cdn.raygun.io/raygun4js/raygun.js\n[min.vanilla]: https://cdn.raygun.io/raygun4js/raygun.vanilla.min.js\n[max.vanilla]: https://cdn.raygun.io/raygun4js/raygun.vanilla.js\n\n## Usage\n\nIf you are using the CDN, be sure to call these usage methods after the installation.\n\nTo send errors manually:\n\n```javascript\ntry {\n  throw new Error('oops');\n}\ncatch(e) {\n  rg4js('send', e);\n}\n```\n\nIn order to get stack traces, you need to wrap your code in a try/catch block like above. Otherwise the error hits ```window.onerror``` handler and may only contain the error message, line number, and column number.\n\nYou also need to throw errors with ```throw new Error('foo')``` instead of ```throw 'foo'```.\n\nTo automatically catch and send unhandled errors, you can attach the automatic window.onerror handler callback:\n\n```javascript\nrg4js('enableCrashReporting', true);\n```\n\nIf you need to detach it (this will disable automatic unhandled error sending):\n\n```javascript\nrg4js('detach');\n```\n\n\n## Documentation\n\n### Initialization Options\n\nTo configure the provider, call this and pass in an options object:\n\n```javascript\nrg4js('options', {\n  // Add some or all of the options below\n});\n```\n\nThe second parameter should contain one or more of these keys and a value to customize the behavior:\n\n`ignoreAjaxAbort` - User-aborted Ajax calls result in errors - if this option is true, these will not be sent.\n\n`ignoreAjaxError` - Ajax requests that return error codes will not be sent as errors to Raygun if this options is true.\n\n`debugMode` - Raygun4JS will log to the console when sending errors.\n\n`wrapAsynchronousCallbacks` - if set to `false`, async callback functions triggered by setTimeout/setInterval will not be wrapped when attach() is called. _Defaults to true_\n\n`ignore3rdPartyErrors` - ignores any errors that have no stack trace information. This will discard any errors that occur completely\nwithin 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line\nand will still be sent. Errors that occur in browser extensions or that have been triggered by bots/crawlers that appear to come from\nyour website will also be ignored. _Note: IE 9 and below have no stacktrace information and errors will be discarded with this enabled._\n\n`excludedHostnames` - Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp\nobjects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested.\n\n`excludedUserAgents` - Prevents errors from being sent from certain user agents by providing an array of strings. This is very helpful to exclude errors reported by certain browsers or test automation with `CasperJS`, `PhantomJS` or any other testing utility that sends a custom user agent. If a part of the client's `navigator.userAgent` matches one of the given strings in the array, then the client will be excluded from error reporting.\n\n`disableErrorTracking` - Stops all errors from being sent to Raygun. This includes errors automatically picked up by global error handlers as well as errors manually sent.\n\n`disablePulse` - Stops real user monitoring events from being sent.\n\n`apiEndpoint` - A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this.\n\n`clientIp` - A string containing the client's IP address. RUM requests will be associated to this IP address when set. Particularly useful when proxying payloads to the Raygun API using the `apiEndpoint` option and maintaining RUM's geographic lookup feature.\n\n_Note: navigator.sendBeacon is used to send RUM payloads when a page is unloading. As such the `clientIp` feature will not associate this last payload._\n\n`pulseMaxVirtualPageDuration` - The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes).\n\n`pulseIgnoreUrlCasing` - Ignore URL casing when sending data to RUM.\n\n`captureUnhandledRejections` - Automatically catch send errors relating to unhandled promise rejections. See [MDN for browser support](https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection).\n\n`setCookieAsSecure` - If the cookies are being used (only used on browsers which don't support localStorage or sessionStorage) then they will be created using the `; secure` flag and thus cookies only work on HTTPS.\n\n`captureMissingRequests` - RUM uses the window.performance API to track XHR timing information and (depending on the browser) not all non-2XX XHR timings are recorded by this API. This option enables the tracking of these missing XHR's calls by tracking the difference between send \u0026 success XHR handlers. This is not enabled by default due these timings being as accurate as the performance API.\n\n`automaticPerformanceCustomTimings` - When enabled Raygun4JS will track each `window.performance.measure` call as a custom timing entry. This enables developers to use a more native API for tracking performance timings. More information about `performance.measure` can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure).\n\n`trackCoreWebVitals` - When enabled, Raygun4JS will automatically track and report Core Web Vitals. This is enabled by default.\n\n`trackViewportDimensions` - When enabled, Raygun4JS will send the browser's viewport dimensions with each RUM session payload. This is enabled by default.\n\nAn example raygun4js configuration:\n\n```javascript\nrg4js('options', {\n  ignoreAjaxAbort: true,\n  ignoreAjaxError: true,\n  debugMode: true,\n  ignore3rdPartyErrors: false,\n  wrapAsynchronousCallbacks: true,\n  excludedHostnames: ['\\.local'],\n  excludedUserAgents: ['Mosaic'],\n  disableErrorTracking: false,\n  disablePulse: false,\n  pulseMaxVirtualPageDuration: 1800000,\n  pulseIgnoreUrlCasing: false,\n  captureUnhandledRejections: true,\n  setCookieAsSecure: false,\n  captureMissingRequests: false,\n  automaticPerformanceCustomTimings: false\n});\n```\n\n### RUM API\n\n#### Tracking Single Page Application (SPA) events\n\nRaygun RUM supports client-side SPAs through the `trackEvent` function:\n\n```javascript\nrg4js('trackEvent', {\n    type: 'pageView',\n    path: '/' + window.location.pathname // Or perhaps window.location.hash\n});\n```\n\nWhen a route or view change is triggered in your SPA, this function should be called with type being `pageView` and `path` set to a string representing the new view or route. RUM will collect up all timing information that is available and send it to the dashboard. These are then viewable as 'virtual pages'.\n\nThe following are a couple of configuration examples that you can use or adapt for your client-side view library/framework. Naturally, if you are using a more full-featured routing system, you should trigger a pageView inside there when the route changes.\n\n**jQuery**\n\n```javascript\n$(window).hashchange(function() {\n  rg4js('trackEvent', {\n      type: 'pageView',\n      path: '/' + location.hash\n  });\n});\n```\n\n**Angular**\n\n```typescript\nexport class AppModule implements OnInit {\n  constructor(private router: Router) {}\n  ngOnInit() {\n    this.router.events.subscribe(event =\u003e {\n      // Track page views when the NavigationEnd event occurs\n      if (event instanceof NavigationEnd) {\n        rg4js('trackEvent', {\n          type: 'pageView',\n          path: event.url\n        });\n      }\n    });\n  }\n}\n```\n\n#### Tracking custom timings\n\nCustom timings allow you to track custom performance measurements across your website and application. For example, you can track the time it takes for a video to play after the user clicks a button or the time for a component to mount.\n\n```javascript\n  rg4js('trackEvent', {\n      type: 'customTiming',\n      name: 'firstInput',\n      duration: 1200,\n  });\n```\nYou can read more about custom timings on its [documentation page here](https://raygun.com/documentation/product-guides/real-user-monitoring/for-web/custom-timings/).\n\n#### Legacy custom timings API\n\n_Note: This API has since been deprecated and will be removed in a future version of the provider. We recommend developers upgrade to using the latest version which is both easier to setup and works for single page applications._\n\n```js\nrg4js('options', {\n  pulseCustomLoadTimeEnabled: true\n  // Plus any other configuration options\n});\n\nrg4js('trackEvent', {\n  type: 'customTimings',\n  timings: {\n    custom1: 10,\n    custom2: 20,\n    custom3: 30,\n    custom4: 40,\n    custom5: 50,\n    custom6: 60,\n    custom7: 70,\n    custom8: 80,\n    custom9: 90,\n    custom10: 10,\n  }\n});\n```\n\n### Breadcrumbs API\n\n#### Breadcrumbs initialization commands\n\nThese should be called if needed during your page's lifecycle:\n\n```javascript\nrg4js('one-of-the-below-options')\n```\n\n`rg4js('disableAutoBreadcrumbs')` - Disable all the automatic breadcrumb integrations (clicks, requests, console logs and navigation events). This has an inverse `enableAutoBreadcrumbs` which is the default\n\n`rg4js('disableAutoBreadcrumbsConsole')` - Disable just automatic breadcrumb creation from console messages\n\n`rg4js('disableAutoBreadcrumbsNavigation')` - Disable just automatic breadcrumb creation from navigation events\n\n`rg4js('disableAutoBreadcrumbsClicks')` - Disable just automatic breadcrumb creation from element clicks\n\n`rg4js('disableAutoBreadcrumbsXHR')` - Disable just automatic breadcrumb creation XMLHttpRequests\n\nAll of the above have an inverse `enableAutoBreadcrumbs\u003ctype\u003e` which is the default\n\n`rg4js('setAutoBreadcrumbsXHRIgnoredHosts', [])` - This can be set to an array of hostnames to not create a breadcrumb for requests/responses to. The values inside the array can either be strings that an indexOf check against the host is made, or regexes which is matched against the host.\n\n`rg4js('setBreadcrumbLevel', 'warning')` - Set the minimum level of breadcrumb to record. This works the same as log levels, you may set it to debug, info, warning and error and it will only keep breadcrumbs with a level equal or above what this is set to. Valid values are one of `['debug', 'info', 'warning', 'error']`. Defaults to info.\n\n`rg4js('logContentsOfXhrCalls', true)` - If set to true will include the body contents of XHR request and responses in Breadcrumb metadata, defaults to false\n\n#### Logging a breadcrumb\n\nBreadcrumbs can be manually logged via `rg4js('recordBreadcrumb', ...)`\n\nThere are two argument formats\n\n`rg4js('recordBreadcrumb', 'breadcrumb-message', {object: 'that will be attached to the breadcrumb custom data'})`\n\nThis is the quickest way to log basic breadcrumbs, requiring only a message and optionally an object to attach some metadata\n\nIf you wish to have further control of the breadcrumb and configure the level (debug, info, warning, error) or set the class/method the breadcrumb was logged from\n\n`rg4js('recordBreadcrumb', {message: 'breadcrumb-message', metadata: {goes: 'here'}, level: 'info', location: 'class:method'})`\n\nYou may use the above argument format\n\n### Unhandled Promise Rejection\n\nAs of 2.10.0 Raygun4JS captures unhandled promise rejections automatically. Browser support for this feature is currently spotty and you can view browser support at [MDN](https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection).\n\nTo disable this functionality by default you can set the `captureUnhandledRejections` key in the [Initialization Options](Initialization Options).\n\nIf you are using a Promise library which contains a global hook for capturing errors you can manually send errors inside of that global hook.\n\n[RSVP.js example:](https://github.com/tildeio/rsvp.js/)\n```javascript\nRSVP.on('error', function(reason) {\n    rg4js('send', {\n      error: reason\n    });\n});\n```\n\nPromise libraries which report unhandled rejections to a global `unhandledrejection` DOM event, like [Bluebird](http://bluebirdjs.com/), are automatically picked up when you have `captureUnhandledRejections` set.\n\n### Dynamic code splitting / loading with Webpack\n\nIf you are using Webpack to perform dynamic code splitting / loading and you are loading your bundles off of a separate domain (ie a cdn) you will need to ensure that you have set the `output.crossOriginLoading` configuration option to `anonymous` to have Raygun4JS pick up your errors without CORS issues. Without this setting the dynamic script tags will be created without a `crossorigin` attribute and be treated by the browser as private information in Raygun4JS's execution context.\n\nExample Webpack config\n\n```javascript\nmodule.exports = {\n  // Other webpack config options\n  output: {\n    // Other output options\n    crossOriginLoading: 'anonymous'\n  },\n};\n\n```\n\n#### Payload size conservation\n\nTo help ensure your payload does not become too large only the most recent 32 breadcrumbs are kept, as well as limiting the size of recorded network request/response texts to 500 characters.\n\n### Multiple Raygun objects on a single page\n\nYou can have multiple Raygun objects in global scope. This lets you set them up with different API keys for instance, and allow you to send different errors to more than one application in the Raygun web app.\n\nTo create a new Raygun object and use it call:\n\n```javascript\nvar secondRaygun = rg4js('getRaygunInstance').constructNewRaygun();\nsecondRaygun.init('apikey');\nsecondRaygun.send(...);\n```\n\nOnly one Raygun object can be attached as the window.onerror handler at one time, as *onerror* can only be bound to one function at once. Whichever Raygun object had `attach()` called on it last will handle the unhandle errors for the page. Note that you should use the V1 API to send using the second Raygun object, and it should be created and called once the page is loaded (for instance in an `onload` callback).\n\n### NoConflict mode\n\nIf you already have an variable called Raygun attached to `window`, you can prevent the provider from overwriting this by enabling NoConflict mode:\n\n```javascript\nrg4js('noConflict', true);\n```\n\nTo then get an instance of the Raygun object when using V2, call this once the page is loaded:\n\n```javascript\nvar raygun = rg4js('getRaygunInstance');\n```\n\nYou can also provide a callback with `'getRaygunInstance'` and it will be called after raygun4js has loaded with the Raygun instance as an argument:\n\n```javascript\nrg4js('getRaygunInstance', raygun =\u003e {\n});\n```\n\n### Callback Events\n\n#### onBeforeSend\n\n```javascript\nrg4js('onBeforeSend', function (payload) {\n  return payload;\n});\n```\n\nCall this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before the payload is sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.\n\nFrom the supplied function, you should return either the payload (intact or mutated as per your needs), or `false`.\n\nIf your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by `filterSensitiveData()`. You can also of course return it as supplied.\n\nIf, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return `false`.\n\nBy example:\n\n```javascript\nvar myBeforeSend = function (payload) {\n  console.log(payload); // Modify the payload here if necessary\n  return payload; // Return false here to abort the send\n}\n\nrg4js('onBeforeSend', myBeforeSend);\n```\n\n#### onBeforeSendRUM\n\n```javascript\nrg4js('onBeforeSendRUM', function (payload) {\n  return payload;\n});\n```\n\nCall this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before any Real User Monitoring events are sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.\n\nFrom the supplied function, you should return either the payload (intact or mutated as per your needs), or `false`.\n\nIf your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs. You can also of course return it as supplied.\n\nIf, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return `false`.\n\nBy example:\n\n```javascript\nvar myBeforeSend = function (payload) {\n  console.log(payload); // Modify the payload here if necessary\n  return payload; // Return false here to abort the send\n}\n\nrg4js('onBeforeSendRUM', myBeforeSend);\n```\n\n#### onAfterSend\n\n```javascript\nrg4js('onAfterSend', function (xhrResponse) {\n  // Inspect the XHR response here\n});\n```\n\nCall this function and pass in a function which takes one parameter (see the example below). This callback function will be immediately called after the XHR request for a Crash Reporting or RUM event responds successfully, or errors out (its `onerror` was called). You can inspect the one parameter, which is the XHR object containing the HTTP response data.\n\n#### onBeforeXHR\n\n```javascript\nrg4js('onBeforeXHR', function (xhr) {\n  // Mutate the xhr parameter as per your needs\n});\n```\n\nCall this function when you want control over the XmlHttpRequest object that is used to send error payloads to the API. Pass in a callback that receives one parameter (which is the XHR object). Your callback will be called after the XHR object is `open`ed, immediately before it is sent.\n\nFor instance, you can use this to add custom HTTP headers.\n\n_Note: `navigator.sendBeacon` is used to send RUM payloads when a page is unloading. In these cases the `onBeforeXHR` method will not be executed as there is no XHR to reference and no additional headers can be attached._\n\n### Custom error grouping\n\nYou can control custom grouping for error instances by passing in a callback. This will override the automatic grouping and be used to group error instances together. Errors with the same key will be placed within the same error group. The callback's signature should take in the error payload, stackTrace and options and return a string, ideally 64 characters or less. If the callback returns null or or a non-string the error will be grouped using Raygun's server side grouping logic (this can be useful if you only wish to use custom grouping for a subset of your errors).\n\n```javascript\nvar groupingKeyCallback = function (payload, stackTrace, options) {\n  // Inspect the above parameters and return a hash derived from the properties you want\n\n  return payload.Details.Error.Message; // Naive message-based grouping only\n};\n\nrg4js('groupingKey', groupingKeyCallback);\n```\n\n### Sending custom data\n\n#### On initialization:\n\nCustom data variables (objects, arrays etc) can be added by calling the withCustomData function on the Raygun object:\n\n```javascript\nrg4js('withCustomData', { foo: 'bar' });\n```\n\n**During a send:**\n\nYou can also pass custom data with manual send calls, with an options object. This lets you add variables that are in scope or global when handled in catch blocks. For example:\n\n```javascript\nrg4js('send', {\n  error: e,\n  customData: [{ foo: 'bar' }]\n});\n```\n\n#### Providing custom data with a callback\n\nTo send the state of variables at the time an error occurs, you can pass withCustomData a callback function. This needs to return an object. By example:\n\n```javascript\nvar desiredNum = 1;\n\nfunction getMyData() {\n return { num: desiredNum };\n}\n\nrg4js('withCustomData', getMyData);\n```\n\n`getMyData` will be called when Raygun4JS is about to send an error, which will construct the custom data. This will be merged with any custom data provided on a Raygun.send() call.\n\n### Adding tags\n\nThe Raygun dashboard can also display tags for errors. These are arrays of strings or Numbers. This is done similar to the above custom data, like so:\n\n**On initialization:**\n\n```javascript\nrg4js('withTags', ['tag1', 'tag2']);\n```\n\n#### During a send:\n\nPass tags in using an options object:\n\n```javascript\nrg4js('send', {\n  error: e,\n  tags: ['tag3'];\n});\n```\n\n#### Adding tags with a callback function\n\nAs above for custom data, `withTags` can now also accept a callback function. This will be called when the provider is about to send, to construct the tags. The function you pass to `withTags` should return an array (ideally of strings/Numbers/Dates).\n\n### Customers\n\nBy default Raygun4JS assigns a unique anonymous ID for the current user. This is stored in local storage and will default back to using a cookie if local storage is not supported. You can remove the ID from storage by calling:\n\n```js\nrg4js('getRaygunInstance').resetAnonymousUser();\n```\n\n#### Disabling anonymous user tracking\n\n```javascript\nrg4js('options', { disableAnonymousUserTracking: true });\n```\n\n#### Rich user data/user tracking\n\nYou can provide additional information about the currently logged in user to Raygun by calling:\n\n```javascript\nrg4js('setUser', {\n  identifier: 'user_email_address@localhost.local',\n  isAnonymous: false,\n  email: 'emailaddress@localhost.local',\n  firstName: 'Foo',\n  fullName: 'Foo Bar',\n  uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55'\n});\n```\n\nOnly `identifier` or the first parameter is required. This method takes additional parameters that are used when reporting over the affected users. The full method signature of the public function and the options object above is:\n\n```javascript\nsetUser: function (user, isAnonymous, email, fullName, firstName, uuid)\n```\n\n`user|identifier` is the user identifier. This will be used to uniquely identify the user within Raygun. This is the only required parameter, but is only required if you are using [Customers](https://raygun.com/documentation/product-guides/customers/).\n\n`isAnonymous` is a bool indicating whether the user is anonymous or actually has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind.\n\n`email` is the user's email address.\n\n`fullName` is the user's full name.\n\n`firstName` is the user's first or preferred name.\n\n`uuid` is the identifier of the device the app is running on. This could be used to correlate user accounts over multiple machines.\n\nThis will be transmitted with each message. A count of unique users will appear on the dashboard in the individual error view. If you provide an email address, the user's Gravatar will be displayed (if they have one). This method is optional; if it is not called, the [Customers](https://raygun.com/documentation/product-guides/customers/) feature is disabled. Note that if the user context changes (such as in an SPA), you should call this method again to update it.\n\n#### Resetting the user\n\nYou can now pass in empty strings (or false to `isAnonymous`) to reset the current user for login/logout scenarios.\n\n### Ending a session\n\nTo end a user's current session:\n\n```javascript\nrg4js('endSession');\n```\n\nThis will end the session for a user and start a new one. The new session will remain attached to the current user.\n\n### Version filtering\n\nYou can set a version for your app by calling:\n\n```javascript\nrg4js('setVersion', '1.0.0.0');\n```\n\nThis will allow you to filter the errors in the dashboard by that version. You can also select only the latest version, to ignore errors that were triggered by ancient versions of your code. The parameter should be a string in the format `x.x.x` if you want to get the version sorting in Raygun to work nicely, where x is a non-negative integer.\n\n### Filtering sensitive data\n\nYou can blacklist keys to prevent their values from being sent it the payload by providing an array of key names:\n\n```javascript\nrg4js('filterSensitiveData', ['password', 'credit_card']);\n```\n\nIf any key matches one in the input array, its value will be replaced with `[removed by filter]`.\n\nYou can also pass RegExp objects in the array to `filterSensitiveData`, for controllable matching of keys:\n\n```javascript\nvar creditCardDataRegex = /credit\\D*/; // Remove any keys that begin with 'credit'\n\nrg4js('filterSensitiveData', [creditCardDataRegex]);\n```\n\n#### Change filter scope\n\nBy default this is applied to the UserCustomData object only (legacy behavior). To apply this to any key-value pair, you can change the filtering scope:\n\n```javascript\nrg4js('setFilterScope', 'all'); // Filter any key in the payload\nrg4js('setFilterScope', 'customData'); // Just filter the custom data (default)\n```\n\n### Source maps support\n\nRaygun4JS now features source maps support through the transmission of column numbers for errors, where available. This is confirmed to work in recent version of Chrome, Safari and Opera, and IE 10 and 11. See the [Raygun souce maps documentation][sourcemaps] for more information.\n\n[sourcemaps]: https://raygun.com/documentation/product-guides/crash-reporting/sourcemaps/\n\n### Offline saving\n\nThe provider has a feature where if errors are caught when there is no network activity they can be saved (in Local Storage). When an error arrives and connectivity is regained, previously saved errors are then sent. This is useful in environments like WinJS, where a mobile device's internet connection is not constant.\n\nOffline saving is **disabled by default.** To change it:\n\n```javascript\nrg4js('saveIfOffline', true);\n```\n\nIf an error is caught and no network connectivity is available (the Raygun API cannot be reached), or if the request times out after 10s, the error will be saved to LocalStorage. This is confirmed to work on Chrome, Firefox, IE10/11, Opera and WinJS.\n\nLimited support is available for IE 8 and 9 - errors will only be saved if the request times out.\n\n### Errors in scripts on other domains\n\nBrowsers have varying behavior for errors that occur in scripts located on domains that are not the origin. Many of these will be listed in Raygun as 'Script Error', or will contain junk stack traces. You can filter out these errors by settings this:\n\n```javascript\nrg4js('options', { ignore3rdPartyErrors: true });\n```\n\n#### Whitelisting domains\n\nThere is also an option to whitelist domains which you **do** want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:\n\n```javascript\nrg4js('options', { ignore3rdPartyErrors: true });\nrg4js('whitelistCrossOriginDomains', ['code.jquery.com']);\n```\n\nThis can be used to allow errors from remote sites and CDNs.\n\nThe provider will default to attempt to send errors from subdomains - for instance if the page is loaded from foo.com, and a script is loaded from cdn.foo.com, that error will be transmitted on a best-effort basis.\n\nTo get full stack traces from cross-origin domains or subdomains, these requirements should be met:\n\n* The remote domain should have `Access-Control-Allow-Origin` set (to include the domain where raygun4js is loaded from).\n\n* For Chrome the `script` tag must also have `crossOrigin=\"Anonymous\"` set.\n\n* Recent versions of Firefox (\u003e= 31) will transmit errors from remote domains will full stack traces if the header is set (`crossOrigin` on script tag not needed).\n\nIn Chrome, if the origin script tag and remote domain do not meet these requirements the cross-origin error will not be sent.\n\nOther browsers may send on a best-effort basis (version dependent) if some data is available but potentially without a useful stacktrace. The provider will cancel the send if no data is available.\n\n## Angular\n\nYou can extend the Angular error handler to send errors directly to Raygun.\n\n```typescript\n// Create a new ErrorHandler and report an issue straight to Raygun\nexport class RaygunErrorHandler implements ErrorHandler {\n  handleError(e: any) {\n    rg4js('send', {\n      error: e,\n    });\n  }\n}\n```\n\n## Vue.js\n\nYou can use the Vue.js error handler to send errors directly to Raygun.\n\nFor Vue.js 2.x, this can be done by setting a global error handler on the `Vue.config.errorHandler` property.\n\n```typescript\n// Vue 2.x example\nVue.config.errorHandler = function(err, vm, info) {\n  rg4js('send', {\n    error: err,\n    customData: [{ info: info }]\n  });\n};\n```\n\nFor Vue.js 3.x, the `.config` property is part of the application instance. You will need to create your application instance first before you can assign the errorHandler property.\n\n```typescript\n// Vue 3.x example\nconst app = Vue.createApp({});\n\napp.config.errorHandler = function(err, vm, info) {\n  rg4js('send', {\n    error: err,\n    customData: [{ info: info }]\n  });\n};\n\napp.mount('#app');\n```\n\n## Release History\n\n[View the changelog here](CHANGELOG.md)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmindscapehq%2Fraygun4js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmindscapehq%2Fraygun4js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmindscapehq%2Fraygun4js/lists"}