history.js 2.3 KB

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