setMutationHandler

MutationObserver wrapper to wait for the specified CSS selector

目前为 2015-10-13 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/12228/80004/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.3
  22. // ==/UserScript==
  23.  
  24. function setMutationHandler(baseNode, selector, cb, options) {
  25. var ob = new MutationObserver(function(mutations) {
  26. for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++)
  27. switch (m.type) {
  28. case 'childList':
  29. for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++)
  30. if (n.nodeType == 1)
  31. if ((n = n.matches(selector) ? [n] : n.querySelectorAll(selector)) && n.length)
  32. if (!cb.call(ob, Array.prototype.slice.call(n)))
  33. return;
  34. break;
  35. case 'attributes':
  36. if (m.target.matches(selector) && !cb.call(ob, [m.target], m))
  37. return;
  38. break;
  39. case 'characterData':
  40. if (m.target.parentNode && m.target.parentNode.matches(selector) && !cb.call(ob, [m.target.parentNode], m))
  41. return;
  42. break;
  43. }
  44. });
  45. ob.observe(baseNode, options || {subtree:true, childList:true});
  46. return ob;
  47. }