By default, Crash Analytics automatically captures JavaScript errors only after the Matomo JavaScript tracker has loaded successfully. If a JavaScript error occurs before the tracker loads, it cannot be reported automatically.

To capture early errors, register a window.onerror handler before the Matomo tracking code. The handler adds the error to the Matomo command queue (_paq), allowing it to be reported once the JavaScript tracker loads.

The following example automatically captures JavaScript errors that occur before the Matomo JavaScript tracker loads by queuing them for reporting once the tracker has initialised:

window._paq = window._paq || [];

window.onerror = function (msg, url, lineNo, columnNo, error) {
    if (!window.Matomo) {
        _paq.push([
            'CrashAnalytics::trackCrash',
            msg,
            'JSError',
            '{CATEGORY}',
            error?.stack,
            url,
            lineNo,
            columnNo
        ]);
    }
};

The if (!window.Matomo) check ensures only errors that occur before the JavaScript tracker has loaded are added to the queue. Once Matomo has initialised, Crash Analytics automatically reports JavaScript errors.