Injecting JavaScript into head element of website using Fiddler

前端 未结 3 2046
死守一世寂寞
死守一世寂寞 2020-12-04 22:05

I was thinking of using Fiddler for the following purpose...

I have a JavaScript based service I want to demonstrate to potential clients. In order to show them wha

相关标签:
3条回答
  • 2020-12-04 22:36

    if you use jQuery you can add js on the fly. I would probably think you can have a method which would include/exclude your script based on some query param. This is how you would include JS with jQuery

    $.getScript('someScript.js',function(){
    //Do something here after your script loads
    });
    
    0 讨论(0)
  • 2020-12-04 22:38

    Haven't tried it, but how about GreaseMonkey for IE?

    0 讨论(0)
  • Open fiddler -> Menu Rules -> Customize Rules (or hit Ctrl+R)

    The CustomRule.js file opens. Scroll down until you find the line

    static function OnBeforeResponse(oSession: Session)
    

    This is where your code goes. Here you can change the server response before the browser sees it.

    The following code sample shows how to include a custom piece of jQuery code which replaces the Unanswered link in the horizontal menu with a link which serves as short cut to Unanswered jQuery Questions

    I first show you the jQuery code I want to include

    <script type='text/javascript'>
        $(function() {
            var newLink = '<a href="/unanswered/tagged/jquery">Unanswered jQuery</a>';
            $('div#hmenus div.nav:first ul li:last a').replaceWith(newLink);
        });
    </script>
    

    Now the fiddler code (based on code found in CustomRules.js and code samples from the FiddlerScript CookBook)

    //is it a html-response and is it from stackoverflow.com
    if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
        oSession.HostnameIs("stackoverflow.com")) {
    
        // Remove any compression or chunking
        oSession.utilDecodeResponse();
    
        var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
    
        // Match the jQuery script tag
        var oRegEx = /(<script[^>]*jquery.min.js"><\/script>)/gi;
        // replace the script tag withitself (no change) + append custom script tag
        oBody = oBody.replace(oRegEx, "$1<script type='text/javascript'>$(function() {$('div#hmenus div.nav:first ul li:last a').replaceWith('<a href=\"/unanswered/tagged/jquery\">Unanswered jQuery</a>');})</script>");
    
        // Set the response body to the changed body string
        oSession.utilSetResponseBody(oBody); 
    }
    

    I think you should now able to hackyourself together a piece of code which fits your problem.

    Example

    // Match the head end
    var oRegEx = /(<\/head>)/gi;
    // replace with new script
    oBody = oBody.replace(oRegEx, "<script type='text/javascript' src='http://url/myscript.js'></script>$1");
    
    0 讨论(0)
提交回复
热议问题