Greasy Fork 支持 简体中文。

Library: Additional DOM Window History-Stack Events (pushstate, replacestate)

Complementing the DOM Window 'popstate' event, this library adds the 'pushstate' and 'replacestate' events and corresponding event handlers ('onpushstate', 'onreplacestate')

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/425774/1060695/Library%3A%20Additional%20DOM%20Window%20History-Stack%20Events%20%28pushstate%2C%20replacestate%29.js

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