Determining Source Line and File of function reference - How does Firebug do it?

前端 未结 2 1407
清酒与你
清酒与你 2021-01-03 03:17

Brief introduction:

I\'m attempting to get at line number of function definition for parsing documentation comments on only public stuff. I\'ve gotten to the point

相关标签:
2条回答
  • 2021-01-03 03:43

    Here's a potential solution that I haven't tested. A couple years ago, there was a security exploit that allowed JavaScript to redeclare constructors of native objects. John Walker gave this example:

    function Array() {
        this[1] = 50;
    }
    var a = [40];
    alert(a[0] + a[1]); // Gives 90
    

    In the same vein, perhaps it's possible to redeclare the function declaration in the browsers where the exploit exists?

    function Function() {
        // Should give the stack trace, complete with line number?
        alert(new Error().stack); 
    }
    
    window.x = function () {}
    

    I don't have the necessary browsers (John Resig cites Firefox 2, Opera 9, and Safari 3 as browsers where the Array exploit works), so I can't test it, but maybe this is a place to start?

    0 讨论(0)
  • 2021-01-03 03:52

    Firebug has access to protected Chrome features that ordinary JS does not.

    But, JS can still access, the raw <script> source, with comments intact, as long as the same-origin policy does not block access.

    For example, this code will get the raw source of all embedded scripts and any scripts loaded from the same domain. :

    var scipts = document.querySelectorAll ('script');
    
    for (var J = 0, L = scipts.length;  J < L;  ++J) {
        console.log ('Number: ', J);
        var node    = scipts[J];
        if (!node)  continue;
    
        if (node.src) {
            //$.get (node.src, function (data) {console.log ('Text: ', data); } );
            try {
                var req = new XMLHttpRequest();
                req.open ('GET', node.src, false);
                req.send (null);
                if (req.status == 200  ||  req.status == 304)
                    console.log ('Text: ', req.responseText);
            }
            catch (err) {
                console.log (err);
            }
        }
        else if (node.innerHTML) {
            console.log ('Text: ', node.innerHTML);
        }
    }
    

    The raw script can then be parsed for line numbers and function definitions, etc.

    0 讨论(0)
提交回复
热议问题