setMutationHandler

MutationObserver wrapper to wait for the specified CSS selector

目前为 2016-07-22 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/12228/137548/setMutationHandler.js

  1. /* EXAMPLE:
  2. setMutationHandler(document, '.container p.some-child', function(nodes) {
  3. // single node:
  4. nodes[0].remove();
  5. // or multiple nodes:
  6. nodes.forEach(function(node) {
  7. node.style.display = 'none';
  8. });
  9.  
  10. //this.disconnect(); // disconnect the observer, this is useful for one-time jobs
  11. return true; // continue enumerating current batch of mutations
  12. });
  13. */
  14.  
  15. // ==UserScript==
  16. // @name setMutationHandler
  17. // @description MutationObserver wrapper to wait for the specified CSS selector
  18. // @namespace wOxxOm.scripts
  19. // @author wOxxOm
  20. // @grant none
  21. // @version 2.0.7
  22. // ==/UserScript==
  23.  
  24. function setMutationHandler(baseNode, selector, cb, options) {
  25. var queue = [];
  26. var timer;
  27. var ob = new MutationObserver(function handler(mutations) {
  28. if (mutations && mutations.length > 100) {
  29. if (!queue.length)
  30. setTimeout(handler, 0);
  31. queue.push(mutations);
  32. return;
  33. }
  34. do {
  35. if (!mutations) {
  36. mutations = queue.shift();
  37. if (!mutations)
  38. return;
  39. }
  40.  
  41. for (var i=0, ml=mutations.length; i < ml; i++) {
  42. var m = mutations[i];
  43. switch (m.type) {
  44. case 'childList':
  45. var nodes = m.addedNodes, nl = nodes.length;
  46. var textNodesOnly = true;
  47. for (var j=0; j < nl; j++) {
  48. var n = nodes[j];
  49. textNodesOnly &= n.nodeType == 3; // TEXT_NODE
  50. if (n.nodeType != 1) // ELEMENT_NODE
  51. continue;
  52. if (n.matches(selector))
  53. n = [n];
  54. else if (n.querySelector(selector))
  55. n = Array.prototype.slice.call(n.querySelectorAll(selector));
  56. else
  57. continue;
  58. if (!cb.call(ob, n, m))
  59. return;
  60. }
  61. if (textNodesOnly && m.target.matches(selector) && !cb.call(ob, [m.target], m))
  62. return;
  63. break;
  64. case 'attributes':
  65. if (m.target.matches(selector) && !cb.call(ob, [m.target], m))
  66. return;
  67. break;
  68. case 'characterData':
  69. if (m.target.parentNode && m.target.parentNode.matches(selector) && !cb.call(ob, [m.target.parentNode], m))
  70. return;
  71. break;
  72. }
  73. }
  74. mutations = null;
  75. } while (queue.length);
  76. });
  77. ob.observe(baseNode, options || {subtree:true, childList:true});
  78. return ob;
  79. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址