history.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. const object = require('../object.js');
  3. require('../debug-build.js');
  4. require('../logger.js');
  5. const worldwide = require('../worldwide.js');
  6. const supportsHistory = require('../vendor/supportsHistory.js');
  7. const _handlers = require('./_handlers.js');
  8. const WINDOW = worldwide.GLOBAL_OBJ ;
  9. let lastHref;
  10. /**
  11. * Add an instrumentation handler for when a fetch request happens.
  12. * The handler function is called once when the request starts and once when it ends,
  13. * which can be identified by checking if it has an `endTimestamp`.
  14. *
  15. * Use at your own risk, this might break without changelog notice, only used internally.
  16. * @hidden
  17. */
  18. function addHistoryInstrumentationHandler(handler) {
  19. const type = 'history';
  20. _handlers.addHandler(type, handler);
  21. _handlers.maybeInstrument(type, instrumentHistory);
  22. }
  23. function instrumentHistory() {
  24. if (!supportsHistory.supportsHistory()) {
  25. return;
  26. }
  27. const oldOnPopState = WINDOW.onpopstate;
  28. WINDOW.onpopstate = function ( ...args) {
  29. const to = WINDOW.location.href;
  30. // keep track of the current URL state, as we always receive only the updated state
  31. const from = lastHref;
  32. lastHref = to;
  33. const handlerData = { from, to };
  34. _handlers.triggerHandlers('history', handlerData);
  35. if (oldOnPopState) {
  36. // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.
  37. // https://github.com/getsentry/sentry-javascript/issues/3344
  38. // https://github.com/bugsnag/bugsnag-js/issues/469
  39. try {
  40. return oldOnPopState.apply(this, args);
  41. } catch (_oO) {
  42. // no-empty
  43. }
  44. }
  45. };
  46. function historyReplacementFunction(originalHistoryFunction) {
  47. return function ( ...args) {
  48. const url = args.length > 2 ? args[2] : undefined;
  49. if (url) {
  50. // coerce to string (this is what pushState does)
  51. const from = lastHref;
  52. const to = String(url);
  53. // keep track of the current URL state, as we always receive only the updated state
  54. lastHref = to;
  55. const handlerData = { from, to };
  56. _handlers.triggerHandlers('history', handlerData);
  57. }
  58. return originalHistoryFunction.apply(this, args);
  59. };
  60. }
  61. object.fill(WINDOW.history, 'pushState', historyReplacementFunction);
  62. object.fill(WINDOW.history, 'replaceState', historyReplacementFunction);
  63. }
  64. exports.addHistoryInstrumentationHandler = addHistoryInstrumentationHandler;
  65. //# sourceMappingURL=history.js.map