Compare commits

...

1 Commits

Author SHA1 Message Date
Cursor Agent
68abaa19ae fix: use Object.defineProperty for history API patching
Fixes FORMBRICKS-FP

The previous implementation tried to directly assign to history.pushState
and history.replaceState, which are read-only properties in some browser
environments. This caused a TypeError: 'Cannot assign to read only property'.

Changes:
- Use Object.defineProperty() to properly override history.pushState
- Add Object.defineProperty() for history.replaceState as well
- Add try-catch error handling for patching failures
- Add proper TypeScript type annotations for patched methods

This fix ensures the Formbricks SDK can properly track page navigation
events without encountering TypeError exceptions.
2026-02-03 16:59:49 +00:00

View File

@@ -83,17 +83,37 @@ export const addPageUrlEventListeners = (): void => {
// Monkey patch history methods if not already done
if (!isHistoryPatched) {
// eslint-disable-next-line @typescript-eslint/unbound-method -- We need to access the original method
const originalPushState = history.pushState;
try {
// eslint-disable-next-line @typescript-eslint/unbound-method -- We need to access the original method
const originalPushState = history.pushState;
// eslint-disable-next-line @typescript-eslint/unbound-method -- We need to access the original method
const originalReplaceState = history.replaceState;
// eslint-disable-next-line func-names -- We need an anonymous function here
history.pushState = function (...args) {
originalPushState.apply(this, args);
const event = new Event("pushstate");
window.dispatchEvent(event);
};
// Use Object.defineProperty to override read-only properties
Object.defineProperty(history, "pushState", {
value: function (...args: Parameters<typeof originalPushState>) {
originalPushState.apply(this, args);
const event = new Event("pushstate");
window.dispatchEvent(event);
},
writable: true,
configurable: true,
});
isHistoryPatched = true;
Object.defineProperty(history, "replaceState", {
value: function (...args: Parameters<typeof originalReplaceState>) {
originalReplaceState.apply(this, args);
const event = new Event("replacestate");
window.dispatchEvent(event);
},
writable: true,
configurable: true,
});
isHistoryPatched = true;
} catch (error) {
console.error("🧱 Formbricks - Failed to patch history methods:", error);
}
}
events.forEach((event) => {