Greasy Fork镜像 is available in English.

setMutationHandler

MutationObserver wrapper to wait for the specified CSS selector

Verze ze dne 10. 10. 2016. Zobrazit nejnovější verzi.

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greasyforks.org/scripts/12228/151756/setMutationHandler.js

/* EXAMPLE:
	
	setMutationHandler(document, '.container p.some-child', function(nodes) {
		// single node:
		nodes[0].remove();
		
		// or multiple nodes:
		nodes.forEach(function(node) {
			node.style.display = 'none';
		});

		//this.disconnect(); // disconnect the observer, this is useful for one-time jobs
	});
*/

// ==UserScript==
// @name          setMutationHandler
// @description   MutationObserver wrapper to wait for the specified CSS selector
// @namespace     wOxxOm.scripts
// @author        wOxxOm
// @grant         none
// @version       2.0.9
// ==/UserScript==

function setMutationHandler(baseNode, selector, cb, options) {
	var ob = new MutationObserver(function MOhandler(mutations) {
		if (mutations.length > 100 && !document.querySelector(selector))
			return;
		var found = [];
		for (var i=0, ml=mutations.length; i < ml; i++) {
			var m = mutations[i];
			switch (m.type) {
				case 'childList':
					var nodes = m.addedNodes, nl = nodes.length;
					var textNodesOnly = true;
					for (var j=0; j < nl; j++) {
						var n = nodes[j];
						textNodesOnly &= n.nodeType == 3; // TEXT_NODE
						if (n.nodeType != 1) // ELEMENT_NODE
							continue;
						if (n.matches(selector))
							found.push(n);
						else if (n.querySelector(selector)) {
							n = n.querySelectorAll(selector);
							if (n.length < 1000)
								found.push.apply(found, n);
							else
								found = found.concat(found.slice.call(n));
						}
					}
					if (textNodesOnly && m.target.matches(selector))
						found.push(m.target);
					break;
				case 'attributes':
					if (m.target.matches(selector))
						found.push(m.target);
					break;
				case 'characterData':
					if (m.target.parentNode && m.target.parentNode.matches(selector))
						found.push(m.target.parentNode);
					break;
			}
		}
		if (found.length)
			cb.call(ob, found);
	});
	ob.observe(baseNode, options || {subtree:true, childList:true});
	return ob;
}
长期地址
遇到问题?请前往 GitHub 提 Issues。