Greasy Fork 支持简体中文。

setMutationHandler

MutationObserver wrapper to wait for the specified CSS selector

目前為 2016-08-14 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/12228/141649/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. });
  12. */
  13.  
  14. // ==UserScript==
  15. // @name setMutationHandler
  16. // @description MutationObserver wrapper to wait for the specified CSS selector
  17. // @namespace wOxxOm.scripts
  18. // @author wOxxOm
  19. // @grant none
  20. // @version 2.0.8
  21. // ==/UserScript==
  22.  
  23. function setMutationHandler(baseNode, selector, cb, options) {
  24. var ob = new MutationObserver(function MOhandler(mutations) {
  25. if (mutations.length > 100 && !document.querySelector(selector))
  26. return;
  27. var found = [];
  28. for (var i=0, ml=mutations.length; i < ml; i++) {
  29. var m = mutations[i];
  30. switch (m.type) {
  31. case 'childList':
  32. var nodes = m.addedNodes, nl = nodes.length;
  33. var textNodesOnly = true;
  34. for (var j=0; j < nl; j++) {
  35. var n = nodes[j];
  36. textNodesOnly &= n.nodeType == 3; // TEXT_NODE
  37. if (n.nodeType != 1) // ELEMENT_NODE
  38. continue;
  39. if (n.matches(selector))
  40. found.push(n);
  41. else if (n.querySelector(selector)) {
  42. n = n.querySelectorAll(selector);
  43. if (n.length < 1000)
  44. found.push.apply(found, n);
  45. else
  46. found = found.concat(n);
  47. }
  48. }
  49. if (textNodesOnly && m.target.matches(selector))
  50. found.push(m.target);
  51. break;
  52. case 'attributes':
  53. if (m.target.matches(selector))
  54. found.push(m.target);
  55. break;
  56. case 'characterData':
  57. if (m.target.parentNode && m.target.parentNode.matches(selector))
  58. found.push(m.target.parentNode);
  59. break;
  60. }
  61. }
  62. if (found.length)
  63. cb.call(ob, found);
  64. });
  65. ob.observe(baseNode, options || {subtree:true, childList:true});
  66. return ob;
  67. }