双击显示密码

双击显示密码,失去焦点隐藏.不覆盖 onload,支持密码框后生成的网站

  1. // ==UserScript==
  2. // @name 双击显示密码
  3. // @namespace https://github.com/Tyrone2333/display-password
  4. // @version 1.3.1
  5. // @description 双击显示密码,失去焦点隐藏.不覆盖 onload,支持密码框后生成的网站
  6. // @author en20
  7. // @include http*://*
  8. // @grant none
  9. // @run-at document-start
  10. // ==/UserScript==
  11. (function () {
  12. function displayPassword() {
  13. let list = document.querySelectorAll("input[type=password]")
  14. for (let i = 0; i < list.length; i++) {
  15. let item = list[i]
  16. item.ondblclick = function () {
  17. item.setAttribute("type", "text")
  18. }
  19. item.onblur = function () {
  20. item.setAttribute("type", "password")
  21. }
  22. }
  23. }
  24.  
  25. // 防止覆盖 onload 事件
  26. function addLoadEvent(func) {
  27. const oldOnload = window.onload
  28. if (typeof window.onload != 'function') {
  29. window.onload = func
  30. } else {
  31. window.onload = function () {
  32. oldOnload()
  33. func()
  34. }
  35. }
  36. }
  37.  
  38. // 防抖,mutationObserver 触发非常频繁
  39. function debounce(fn, delay) {
  40. // console.log(args)
  41. let timer = null
  42.  
  43. return function (...args) {
  44.  
  45. clearTimeout(timer)
  46.  
  47. timer = setTimeout(() => {
  48.  
  49. fn.call(this, ...args)
  50.  
  51. }, delay)
  52. }
  53. }
  54.  
  55. // 保存旧版 MutationObserver,防止如百度之类站点覆盖 MutationObserver
  56. function preserveMutationObserver() {
  57. window.preserveMutationObserver = window.MutationObserver
  58. }
  59.  
  60. function addMutationObserver() {
  61. const MutationObserver = window.preserveMutationObserver || window.MutationObserver
  62. // 监听每次 dom 变化,重新寻找密码框添加事件
  63. const mutationObserver = new MutationObserver(debounce((mutations) => {
  64. displayPassword()
  65. // mutations.forEach(function (mutation) {
  66. // console.log(mutation.addedNodes)
  67. // })
  68. }, 300))
  69.  
  70. // 开始监听页面根元素 HTML 变化。
  71. mutationObserver.observe(document.documentElement, {
  72. attributes: true,
  73. characterData: true,
  74. childList: true,
  75. subtree: true,
  76. attributeOldValue: true,
  77. characterDataOldValue: true,
  78. })
  79. }
  80.  
  81. preserveMutationObserver()
  82.  
  83. addLoadEvent(displayPassword)
  84. addLoadEvent(addMutationObserver)
  85.  
  86. })()