UserScript | Library: DOM Window History Stack Events (pushstate/replacestate)

To complement the <window> 'popstate' event, this library adds the 'pushstate'/'replacestate' events to <window>. Also adds corresponding 'onpushstate'/'onreplacestate' event handlers.

当前为 2021-05-01 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/425774/926820/UserScript%20%7C%20Library%3A%20DOM%20Window%20History%20Stack%20Events%20%28pushstatereplacestate%29.js

  1. // ==UserScript==
  2. // @name UserScript | Library: DOM Window History Stack Events (pushstate/replacestate)
  3. // @namespace de.sidneys.userscripts
  4. // @homepage https://gist.githubusercontent.com/sidneys/fb1cdcf6fa7eef8df903cc8c178e4144/raw/
  5. // @version 0.0.8
  6. // @description To complement the <window> 'popstate' event, this library adds the 'pushstate'/'replacestate' events to <window>. Also adds corresponding 'onpushstate'/'onreplacestate' event handlers.
  7. // @author sidneys
  8. // @icon https://i.imgur.com/nmbtzlX.png
  9. // @include *://*/*
  10. // ==/UserScript==
  11.  
  12. /**
  13. * @overview
  14. *
  15. * @see {@link https://stackoverflow.com/a/4585031/1327892}
  16. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/History/pushState}
  17. */
  18.  
  19. /**
  20. * @public
  21. *
  22. * Emits a 'pushstate' event from <window> by Monkey-Patching History.pushState().
  23. * Calls corresponding window#onpushstate event handler.
  24. *
  25. * @mixin window.onpushstate
  26. */
  27. const originalPushState = window.history.pushState
  28. window.history.pushState = (state, title = '', url) => {
  29. // Create event
  30. const event = new Event('pushstate', { bubbles: false, composed: false })
  31. event.state = state
  32.  
  33. // Emit event
  34. window.dispatchEvent(event)
  35.  
  36. // Call 'on'-prefixed event handler method
  37. if (typeof window.onpushstate === 'function') {
  38. window.onpushstate(event)
  39. }
  40. // Call original method
  41. originalPushState.call(window.history, state, title, url)
  42. }
  43.  
  44. /**
  45. * @public
  46. *
  47. * Emits a 'replacestate' event from <window> by Monkey-Patching History.replaceState().
  48. * Calls corresponding window#onreplacestate event handler.
  49. *
  50. * @mixin window.onreplacestate
  51. */
  52. const originalReplaceState = window.history.replaceState
  53. window.history.replaceState = (state, title = '', url) => {
  54. // Create event
  55. const event = new Event('replacestate', { bubbles: false, composed: false })
  56. event.state = state
  57.  
  58. // Emit event
  59. window.dispatchEvent(event)
  60.  
  61. // Call 'on'-prefixed event handler method
  62. if (typeof window.onreplacestate === 'function') {
  63. window.onreplacestate(event)
  64. }
  65. // Call original method
  66. originalReplaceState.call(window.history, state, title, url)
  67. }