Home

Mark Textnodes

Source code for bookmarklet Mark Textnodes.



javascript:
(function(){
        function travTree(node, ifun)
    {
        var counter = 0;
        function ns(nxi, level)
        {
            var nx = nxi;
            while (nx)
            {
                ++counter;
                ifun(nx);
                ns(nx.firstChild, level + 1);
                nx = level > 0 ? nx.nextSibling : null;
            }
        }

        ns( node, 0 );
        return counter;
    }
    var rp = 0;

    var found = [];
    var currDoc;
    var tl = 0;

    function eN(n)
    {
        if ( n.data != null
            && n.nodeType != 8 // COMMENT_NODE
            && n.nodeType != 4 // CDATA_SECTION_NODE
            && n.parentNode.tagName != "SCRIPT" && /\S+/.test(n.data))
        {
            tl += n.data.length;
            found.push([n, currDoc]);
        }
    }
    
    var bodies = [];

    function eD(dt, f) {
        currDoc = dt;
        var bod = dt.getElementsByTagName("BODY")[0];
        if (bod)
        {
            bodies.push( bod );
            travTree(bod, eN);
        }
    }


    // "dIr" == "documentIterator"
    function dIr(dt, f) {
        function ifsr( fs )
        {
            for (var i = 0; i < fs.length; ++i)
            {
                try {
                    dIr(fs[i].contentDocument, fs[i]); // recursive call
                }
                catch (e) {
                    alert(e || "Unspecified error");
                }
            }
        }

        if (dt == null) {return;}
        eD(dt, f);
        ifsr( dt.getElementsByTagName("FRAME") );
        ifsr( dt.getElementsByTagName("IFRAME") );
    }

    // iterate through all documents
    dIr(document, null);

    for (var i = 0; i < found.length; ++i)
    {
        var node = found[i];
        var n = node[0];
        var dt = node[1];

        var sp = dt.createElement("SPAN");
        sp.style.border = "thin solid red";
        sp.appendChild( dt.createTextNode(n.data) );
        n.parentNode.replaceChild(sp, n);
        ++rp;
    }

    for (var i = 0; i < bodies.length; ++i)
    {
        bodies[i].style.visibility = "hidden";
        bodies[i].style.visibility = "visible";
    }

    alert("Textnodes: " + rp + " (bytes: " + tl + ", bytes/node: "
        + (rp > 0 ? Math.ceil(tl/rp) : "N/A")
        + ").");
}());