H5 代码调试大法

1、PC端项目

用Chrome调试工具能解决大部分问题
  • monitorEvents($0,eventType),该API可监控$0元素上触发的eventType类型的事件
    https://briangrinstead.com/blog/chrome-developer-tools-monitorevents/
  • js错误捕获
    你写的js报错你能忍?反正我不能忍

怎么办呢,把错误捕获就OK啦

  1. 同步代码运行时异常(非异步代码,无语法错误)
    用try,catch包裹就完事了
  2. 异步代码(setTimeout等)和语法错误
window.onerror = function(message, source, lineno, colno, error){
  console.log(lineno+'行捕获到异常:',message,source,error);
  return true; //阻止异常继续向上抛
}
setTimeout(function(){ throw Error("oh no!") }, 0)
  1. promise产生的异常
    在new promise时链式调用.catch就可以捕获到异常。或者用
window.addEventListener("unhandledrejection", function(e){
  // Event新增属性
  // @prop {Promise} promise - 状态为rejected的Promise实例
  // @prop {String|Object} reason - 异常信息或rejected的内容
  // 会阻止异常继续抛出,不让Uncaught(in promise) Error产生
  e.preventDefault()
})
  1. 网络请求异常,如404等
window.addEventListener("error", function(e){
  console.log('网络错误:'+e) // 回显false
}, true)

2、移动端项目

  • vconsole
    该插件能在手机端查看:
    1、后台接口请求,
    2、index.html引入了哪些文件;
    3、html的element;
    4、查看具体css、js源文件
    缺陷:不能抓js.css.图片等静态资源的包,只能抓ajax包
    用法: 引入以下js文件即可
//js引入


H5 代码调试大法_第1张图片
  • Fiddle
    Fiddle几乎什么包都能抓,只是使用时要设代理,稍微麻烦点
    IPhone设置fidder代理
    1、 设置-无线局域网-HTTP代理(手动)-服务器(填写本机IP地址,比如10.2.136.85),端口8888
    2、 在浏览器打开本机IP+端口,比如10.2.136.85:8888,此时会要求你安装证书,选择安装
    3、 设置-通用-关于本机-证书信任设置-打开信任证书开关
    4、 打开fidder,在手机上进入任何应用都会被记录
  • Fidder 的原理:
    当不设置代理时,手机上打开一个网页是通过自己手机的网络访问的
    当设置代理时,手机上打开网页是通过你代理设置的IP网络访问的,一般也就是通过自己本机地址访问的,在电脑上打开fidder,fidder就可以通过8888端口监听到手机上的请求(fidder的设置项中有设置用哪个端口监听,Tools-options-connections)


    H5 代码调试大法_第2张图片
    fidder.png

    Fidder的作用
    1、 线上代码映射到本地代码
    当把代码上传到服务器了,如果想改代码,可以做到本地修改代码看效果,不用将代码上传到服务器才看到效果,用到的是fidder的AutoResponder


    H5 代码调试大法_第3张图片
    image.png

    bpafter https://ink-staging.sohusce.com/h5/info-detail/detail.html?message_id=9225
    a--jump https://ink.sohu.com/h5/info-detail/detail.html?message_id=9225

    HTTP/1.1 302 OK
    Server: nginx
    Date: Wed, 04 Apr 2018 14:16:43 GMT
    Content-Type: text/html; charset=utf-8
    Connection: keep-alive
    Last-Modified: Wed, 04 Apr 2018 13:43:15 GMT
    Expires: Thu, 05 Apr 2018 14:16:43 GMT
    Cache-Control: max-age=86400
    Content-Length: 1366
    Location: https://ink.sohu.com/h5/info-detail/detail.html?message_id=9225

    // 自定义fidder输出
    /*!
     * Fiddler CustomRules
     * @Version 1.0.0
     * @Author xxxily
     * @home https://github.com/xxxily/Fiddler-plus
     * @bugs https://github.com/xxxily/Fiddler-plus/issues
     */
    
    /**
     * 全局配置项
     * 可配置链接类型的颜色,代理、替换地址等,
     * 默认对象的键【key】为要匹配的规则,值【key】为匹配后的配置
     */
    var GLOBAL_SETTING:Object = {
        // 开启或禁止缓存
        disableCaching:false,
        // 过滤配置【用于过滤出哪些URL需要显示,哪些需要隐藏】
        Filter:{
            // 只显示URL包含以下字符的连接
            showLinks:[
            //  "fe.w.sohu.com",
              //  "fe.ink.sohu.com",
    //  "ink.sohu.com",
            //  "cdn.sohusce.com",
            //  "10.2.138.70",
            //  "cdn.sohucs.com",
            //  "scdn.itc.cn",
    //  "cdn.mxpnl.com",
    //  "ink-test.sce.sohuno.com",
    //  "ink.sce.sohuno.com",
    //  "sns-dev.bjcnc.img.sohucs.com",
    //  "527920a520000.cdn.sohucs.com",
    //  "ink-public.bjcnc.img.sohucs.com",
    //  "ink-backflow.sce.sohuno.com"
            //     "baidu.com",
                // "youdao.com"
            ],
            // 隐藏URL包含以下字符串的连接 过滤
            hideLinks:[
    
            ],
            // 只显示以下文件类型【注意:是根据header的 Content-Type字段进行匹配的,所以js文件直接写js是不行的,但支持模糊匹配 】
            // 附注:使用ContentType过滤的时候不一定准确,不带 ContentType的连接会被自动隐藏,该过滤选项的逻辑还有待优化和完善
            showContentType:[
                // "image",
                //"css",
               // "html",
              //  "javascript"
           ],
            // 隐藏以下文件类型
            hideContentType:[
                //"css",
                //"html",
                //"javascript"
            ]
        },
        // 替换URL【可用于多环境切换、解决跨域、快速调试线上脚本等】
        replace:{
            "":""
        },
    
        // 界面显示配置【可以对不同链接进行颜色标识,以便快速定位相关链接】
        UI:{
            // 默认文本颜色
            color:"white",//灰白色
            // 默认背景颜色
            bgColor:"black",//浅黑
            bgColor_02:"#2f2f2f",//浅黑【用于做交替背景,可以不设置】
            // bgColor_02:"#4b4a4a",
            // 链接返回报错时的颜色
            onError:{
                // bgColor:"#2c2c2c",
                color:"#FF0000" //错误红
                // ,bold:"true"
            },
            // 不同关键词匹配对应的连接颜色,key 对应的是匹配的关键字,val对应的是匹配的颜色
            linkColor:{
                "\\.jpg|\\.png|\\.gif":"#ffccff", //粉紫色
                "\\.js":"#00ff00", //原谅色
                "\\.css":"#ffcc66", //米黄
                "\\.html":"#00d7ff", //蓝色
                "\\.php":"#fff32d", //大黄
                "\\.jsp":"#fd4107" //砖红
            },
            // 可以为特殊状态码设置不同颜色,方便快速定位一些错误链接,例如404等
            // 注意:这个只是根据responseCode 来匹配的,一些不存在response的链接配置是无效的,例如 502,504状态,应该是在onError里配置的
            statusCode:{
                "404|408|500|502|504":"#FF0000", //错误红
                "304":"#5e5e5e" //浅灰色
            },
            // 高亮,对特殊的链接进行高亮设置,方便跟踪查看链接
            highlight:{
                "http://localhost|192.168":{
                    // bgColor:"#2c2c2c", //浅黑
                    color:"#00ff00", //原谅色
                    bold:"true",
                    describe:"高亮测试"
                },
                "hm.baidu.com":{
                    bgColor:"#FF0000", //红色
                    color:"#fdf404", //黄色
                    bold:"true",
                    describe:"高亮测试"
                },
                "":""
            }
        },
        // 一些实用工具集,先列个可能会开发的工具集,留个坑以后有时间再开发
        Tools:{
            // TODO API 测试工具
            apiTest:{},
            // TODO 重放攻击工具
            replay:{},
            // TODO js 格式化工具
            jsFormat:{},
            // TODO css 格式化工具
            cssFormat:{},
            // TODO 内容注入工具
            contentInject:{},
            // TODO 类似 weinre 这样的注入调试工具
            weinre:{}
        },
        // 多项分隔符号【同一个配置需匹配多项规则时可以通过分隔符进行区分,这样就不用每个规则都要新开一份配置那么繁琐】
        splitStr:"|",
        // 正则匹配的修饰符:i,g,m 默认i,不区分大小写
        regAttr:"i"
    };
    //全局配置项 END
    
    
    
    // 调试方法 BEGIN
    if( !console ){
        var console = {} ;
        console.log = function (arg1,arg2,arg3,arg4,arg5,arg6) {
    
            // 不支持 arguments ,尴尬!
            var args = [arg1,arg2,arg3,arg4,arg5,arg6] ;
            var argsLen = 0 ;
            for( var i = 0 ; i < args.length ; i++ ){
                var arg = args[i] ;
                if( typeof arg === "undefined"){
                    break ;
                }
                argsLen += 1 ;
    
                var argType = typeof arg ;
    
                if( argType === "string" || argType === "number" ){
                    FiddlerObject.log( arg );
                }else if( argType === "boolean"){
                    FiddlerObject.log( "boolean:"+arg );
                }else if( argType === "object" && arg.toString ){
                    FiddlerObject.log( arg.toString() );
                }else {
                    try {
                        FiddlerObject.log( "尝试遍历输出:"+argType );
                        for( var str = "" in arg ){
                            FiddlerObject.log( str+":"+arg[str] );
                        }
                    }catch (ex){
                        FiddlerObject.log( "遍历输出失败:"+ex );
                        FiddlerObject.log( arg );
                    }
                }
            }
            if(argsLen > 1){
                FiddlerObject.log( "----------------------------------------------" );
            }
        }
    }
    if( !alert ){
        var alert = FiddlerObject.alert ;
    }
    // 调试方法 END
    
    
    import System;
    import System.Windows.Forms;
    import Fiddler;
    // INTRODUCTION
    //
    // Well, hello there!
    //
    // Don't be scared! :-)
    //
    // This is the FiddlerScript Rules file, which creates some of the menu commands and
    // other features of Fiddler. You can edit this file to modify or add new commands.
    //
    // The original version of this file is named SampleRules.js and it is in the
    // \Program Files\Fiddler\ folder. When Fiddler first runs, it creates a copy named
    // CustomRules.js inside your \Documents\Fiddler2\Scripts folder. If you make a
    // mistake in editing this file, simply delete the CustomRules.js file and restart
    // Fiddler. A fresh copy of the default rules will be created from the original
    // sample rules file.
    
    // The best way to edit this file is to install the FiddlerScript Editor, part of
    // the free SyntaxEditing addons. Get it here: http://fiddler2.com/r/?SYNTAXVIEWINSTALL
    
    // GLOBALIZATION NOTE: Save this file using UTF-8 Encoding.
    
    // JScript.NET Reference
    // http://fiddler2.com/r/?msdnjsnet
    //
    // FiddlerScript Reference
    // http://fiddler2.com/r/?fiddlerscriptcookbook
    
    class Handlers
    {
        // *****************
        //
        // This is the Handlers class. Pretty much everything you ever add to FiddlerScript
        // belongs right inside here, or inside one of the already-existing functions below.
        //
        // *****************
    
        // The following snippet demonstrates a custom-bound column for the Web Sessions list.
        // See http://fiddler2.com/r/?fiddlercolumns for more info
        /*
         public static BindUIColumn("Method", 60)
         function FillMethodColumn(oS: Session): String {
         return oS.RequestMethod;
         }
         */
    
        // The following snippet demonstrates how to create a custom tab that shows simple text
        /*
         public BindUITab("Flags")
         static function FlagsReport(arrSess: Session[]):String {
         var oSB: System.Text.StringBuilder = new System.Text.StringBuilder();
         for (var i:int = 0; i 0 ){
                var rpLen = replacePlus.length ;
                for( var i = 0 ; i < rpLen ; i++ ){
                    var rpSettingItem = replacePlus[i] ;
                    if( rpSettingItem.enabled === true && rpSettingItem.replaceWith ){
                        settingMatch(oSession.fullUrl,rpSettingItem.source,function( conf,matchStr ){
                            var newUrl = System.Text.RegularExpressions.Regex.Replace(oSession.fullUrl, matchStr , rpSettingItem.replaceWith) ;
                            if( rpSettingItem.urlContain || rpSettingItem.urlUnContain ){
                                // 进行二级匹配
    
                                settingMatch( oSession.fullUrl,rpSettingItem.urlContain,function( matchStr02 ){
                                    oSession.fullUrl = newUrl ;
                                    setSessionDisplay( oSession,rpSettingItem );
                                },"【replacePlus里面的urlContain】配置出错,请检查你的配置");
    
                                settingUnMatch( oSession.fullUrl,rpSettingItem.urlUnContain,function( matchStr02 ){
                                    oSession.fullUrl = newUrl ;
                                    setSessionDisplay( oSession,rpSettingItem );
                                },"【replacePlus里面的urlUnContain】配置出错,请检查你的配置");
    
                            }else {
                                oSession.fullUrl = newUrl ;
                                setSessionDisplay( oSession,rpSettingItem );
                            }
                        },"【replacePlus】配置出错,请检查你的配置");
                    }
                }
            }
    
            // 接管替换URL END
    
            // Sample Rule: Color ASPX requests in RED
            // if (oSession.uriContains(".aspx")) { oSession["ui-color"] = "red";   }
    
            // Sample Rule: Flag POSTs to fiddler2.com in italics
            // if (oSession.HostnameIs("www.fiddler2.com") && oSession.HTTPMethodIs("POST")) {  oSession["ui-italic"] = "yup";  }
    
            // Sample Rule: Break requests for URLs containing "/sandbox/"
            // if (oSession.uriContains("/sandbox/")) {
            //     oSession.oFlags["x-breakrequest"] = "yup";   // Existence of the x-breakrequest flag creates a breakpoint; the "yup" value is unimportant.
            // }
    
            // 通过QuickExec 输入字符串来筛选出要高亮的url
            if( (null != filter_and_highlight_url) && oSession.uriContains( filter_and_highlight_url ) ){
                oSession["ui-color"] = "#FF0000" ;
                oSession["ui-bold"]="true";
            }
    
            if ((null != gs_ReplaceToken) && (oSession.fullUrl.indexOf(gs_ReplaceToken)>-1)) {   // Case sensitive
                oSession.fullUrl = oSession.fullUrl.Replace(gs_ReplaceToken, gs_ReplaceTokenWith);
            }
            if ((null != gs_OverridenHost) && (oSession.host.toLowerCase() == gs_OverridenHost)) {
                oSession["x-overridehost"] = gs_OverrideHostWith;
            }
    
            if ((null!=bpRequestURI) && oSession.uriContains(bpRequestURI)) {
                oSession["x-breakrequest"]="uri";
            }
    
            if ((null!=bpMethod) && (oSession.HTTPMethodIs(bpMethod))) {
                oSession["x-breakrequest"]="method";
            }
    
            if ((null!=uiBoldURI) && oSession.uriContains(uiBoldURI)) {
                oSession["ui-bold"]="QuickExec";
            }
    
            if (m_SimulateModem) {
                // Delay sends by 300ms per KB uploaded.
                oSession["request-trickle-delay"] = "300";
                // Delay receives by 150ms per KB downloaded.
                oSession["response-trickle-delay"] = "150";
            }
    
            if (m_DisableCaching || GLOBAL_SETTING.disableCaching) {
                oSession.oRequest.headers.Remove("If-None-Match");
                oSession.oRequest.headers.Remove("If-Modified-Since");
                oSession.oRequest["Pragma"] = "no-cache";
            }
    
            // User-Agent Overrides
            if (null != sUA) {
                oSession.oRequest["User-Agent"] = sUA;
            }
    
            if (m_Japanese) {
                oSession.oRequest["Accept-Language"] = "ja";
            }
    
            if (m_AutoAuth) {
                // Automatically respond to any authentication challenges using the
                // current Fiddler user's credentials. You can change (default)
                // to a domain\\username:password string if preferred.
                //
                // WARNING: This setting poses a security risk if remote
                // connections are permitted!
                oSession["X-AutoAuth"] = "(default)";
            }
    
            if (m_AlwaysFresh && (oSession.oRequest.headers.Exists("If-Modified-Since") || oSession.oRequest.headers.Exists("If-None-Match")))
            {
                oSession.utilCreateResponseAndBypassServer();
                oSession.responseCode = 304;
                oSession["ui-backcolor"] = "Lavender";
            }
        }
        //OnBeforeRequest END
    
        // This function is called immediately after a set of request headers has
        // been read from the client. This is typically too early to do much useful
        // work, since the body hasn't yet been read, but sometimes it may be useful.
        //
        // For instance, see
        // http://blogs.msdn.com/b/fiddler/archive/2011/11/05/http-expect-continue-delays-transmitting-post-bodies-by-up-to-350-milliseconds.aspx
        // for one useful thing you can do with this handler.
        //
        // Note: oSession.requestBodyBytes is not available within this function!
        /*
         static function OnPeekAtRequestHeaders(oSession: Session) {
         var sProc = ("" + oSession["x-ProcessInfo"]).ToLower();
         if (!sProc.StartsWith("mylowercaseappname")) oSession["ui-hide"] = "NotMyApp";
         }
         */
    
        //
        // If a given session has response streaming enabled, then the OnBeforeResponse function
        // is actually called AFTER the response was returned to the client.
        //
        // In contrast, this OnPeekAtResponseHeaders function is called before the response headers are
        // sent to the client (and before the body is read from the server).  Hence this is an opportune time
        // to disable streaming (oSession.bBufferResponse = true) if there is something in the response headers
        // which suggests that tampering with the response body is necessary.
        //
        // Note: oSession.responseBodyBytes is not available within this function!
        //
        static function OnPeekAtResponseHeaders(oSession: Session) {
    
            //FiddlerApplication.Log.LogFormat("Session {0}: Response header peek shows status is {1}", oSession.id, oSession.responseCode);
            if (m_DisableCaching  || GLOBAL_SETTING.disableCaching) {
                oSession.oResponse.headers.Remove("Expires");
                oSession.oResponse["Cache-Control"] = "no-cache";
            }
    
            if ((bpStatus>0) && (oSession.responseCode == bpStatus)) {
                oSession["x-breakresponse"]="status";
                oSession.bBufferResponse = true;
            }
    
            if ((null!=bpResponseURI) && oSession.uriContains(bpResponseURI)) {
                oSession["x-breakresponse"]="uri";
                oSession.bBufferResponse = true;
            }
    
        }
    
        static function OnBeforeResponse(oSession: Session) {
    
            // 过滤出需要显示或隐藏的连接 BEGIN
    
            var contentType = oSession.oResponse["Content-Type"],
                showContentType = GLOBAL_SETTING.Filter.showContentType,
                hideContentType = GLOBAL_SETTING.Filter.hideContentType;
    
            //开启了 ContentType 过滤的时候, 把不带 Content-Type 全部过滤掉
            if( !contentType && showContentType.length > 0 ){
                console.log("隐藏不带 ContentType 的连接");
                hideLink( oSession );
            }
    
            // 过滤出要显示的连接,把不在显示列表里的连接隐藏掉
            settingUnMatch(contentType,showContentType,function(){
                hideLink( oSession );
            },"【showContentType】配置出错,请检查你的配置");
    
            // 过滤出要隐藏的连接,把在隐藏列表里的连接隐藏掉
            settingMatch(contentType,hideContentType,function( conf,matchStr ){
                hideLink( oSession );
                return true ;
            },"【hideContentType】配置出错,请检查你的配置");
    
            // 过滤出需要显示或隐藏的连接 END
    
            // 根据不同状态码设置链接颜色
            var statusCode = GLOBAL_SETTING.UI.statusCode ;
            settingMatch(oSession.responseCode,statusCode,function( conf,matchStr ){
                oSession["ui-color"] = GLOBAL_SETTING.UI.color ;
                conf ? oSession["ui-color"] = conf : "" ;
                return true ;
            },"【statusCode】配置出错,请检查你的配置");
    
            if (m_Hide304s && oSession.responseCode == 304) {
                oSession["ui-hide"] = "true";
            }
    
        }
        //OnBeforeResponse END
    
        // 请求完成时的回调
        static function OnDone(oSession: Session) {
            //
        }
    
        /**
         * 链接返回出错时的回调方法
         */
        static function OnReturningError(oSession: Session) {
            // 出错时的颜色配置
            var onErrorConf = GLOBAL_SETTING.UI.onError ;
            !onErrorConf.bgColor ? onErrorConf.bgColor = GLOBAL_SETTING.UI.bgColor : "" ;
            setSessionDisplay( oSession,onErrorConf );
        }
    
        /*
         // This function executes just before Fiddler returns an error that it has
         // itself generated (e.g. "DNS Lookup failure") to the client application.
         // These responses will not run through the OnBeforeResponse function above.
         static function OnReturningError(oSession: Session) {
         }
         */
        /*
         // This function executes after Fiddler finishes processing a Session, regardless
         // of whether it succeeded or failed. Note that this typically runs AFTER the last
         // update of the Web Sessions UI listitem, so you must manually refresh the Session's
         // UI if you intend to change it.
         static function OnDone(oSession: Session) {
         }
         */
    
        /*
         static function OnBoot() {
         MessageBox.Show("Fiddler has finished booting");
         System.Diagnostics.Process.Start("iexplore.exe");
    
         UI.ActivateRequestInspector("HEADERS");
         UI.ActivateResponseInspector("HEADERS");
         }
         */
    
        /*
         static function OnBeforeShutdown(): Boolean {
         // Return false to cancel shutdown.
         return ((0 == FiddlerApplication.UI.lvSessions.TotalItemCount()) ||
         (DialogResult.Yes == MessageBox.Show("Allow Fiddler to exit?", "Go Bye-bye?",
         MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)));
         }
         */
    
        /*
         static function OnShutdown() {
         MessageBox.Show("Fiddler has shutdown");
         }
         */
    
        /*
         static function OnAttach() {
         MessageBox.Show("Fiddler is now the system proxy");
         }
         */
    
        /*
         static function OnDetach() {
         MessageBox.Show("Fiddler is no longer the system proxy");
         }
         */
    
        // The Main() function runs everytime your FiddlerScript compiles
        static function Main() {
            var today: Date = new Date();
            FiddlerObject.StatusText = " CustomRules.js was loaded at: " + today;
    
            // Uncomment to add a "Server" column containing the response "Server" header, if present
            // UI.lvSessions.AddBoundColumn("Server", 50, "@response.server");
    
            // Uncomment to add a global hotkey (Win+G) that invokes the ExecAction method below...
            // UI.RegisterCustomHotkey(HotkeyModifiers.Windows, Keys.G, "screenshot");
        }
    
        // These static variables are used for simple breakpointing & other QuickExec rules
        BindPref("fiddlerscript.ephemeral.bpRequestURI")
        public static var bpRequestURI:String = null;
    
        BindPref("fiddlerscript.ephemeral.bpResponseURI")
        public static var bpResponseURI:String = null;
    
        BindPref("fiddlerscript.ephemeral.bpMethod")
        public static var bpMethod: String = null;
    
        static var bpStatus:int = -1;
        static var uiBoldURI: String = null;
        static var gs_ReplaceToken: String = null;
        static var gs_ReplaceTokenWith: String = null;
        static var gs_OverridenHost: String = null;
        static var gs_OverrideHostWith: String = null;
        static var filter_and_highlight_url: String = null; //根据匹配的字符来高亮筛选出的url
    
        // The OnExecAction function is called by either the QuickExec box in the Fiddler window,
        // or by the ExecAction.exe command line utility.
        static function OnExecAction(sParams: String[]): Boolean {
    
            FiddlerObject.StatusText = "ExecAction: " + sParams[0];
    
            var sAction = sParams[0].toLowerCase();
            switch (sAction) {
                case "bold":
                    if (sParams.Length<2) {uiBoldURI=null; FiddlerObject.StatusText="Bolding cleared"; return false;}
                    uiBoldURI = sParams[1]; FiddlerObject.StatusText="Bolding requests for " + uiBoldURI;
                    return true;
                case "bp":
                    FiddlerObject.alert("bpu = breakpoint request for uri\nbpm = breakpoint request method\nbps=breakpoint response status\nbpafter = breakpoint response for URI");
                    return true;
                case "bps":
                    if (sParams.Length<2) {bpStatus=-1; FiddlerObject.StatusText="Response Status breakpoint cleared"; return false;}
                    bpStatus = parseInt(sParams[1]); FiddlerObject.StatusText="Response status breakpoint for " + sParams[1];
                    return true;
                case "bpv":
                case "bpm":
                    if (sParams.Length<2) {bpMethod=null; FiddlerObject.StatusText="Request Method breakpoint cleared"; return false;}
                    bpMethod = sParams[1].toUpperCase(); FiddlerObject.StatusText="Request Method breakpoint for " + bpMethod;
                    return true;
                case "bpu":
                    if (sParams.Length<2) {bpRequestURI=null; FiddlerObject.StatusText="RequestURI breakpoint cleared"; return false;}
                    bpRequestURI = sParams[1];
                    FiddlerObject.StatusText="RequestURI breakpoint for "+sParams[1];
                    return true;
                case "bpa":
                case "bpafter":
                    if (sParams.Length<2) {bpResponseURI=null; FiddlerObject.StatusText="ResponseURI breakpoint cleared"; return false;}
                    bpResponseURI = sParams[1];
                    FiddlerObject.StatusText="ResponseURI breakpoint for "+sParams[1];
                    return true;
                case "overridehost":
                    if (sParams.Length<3) {gs_OverridenHost=null; FiddlerObject.StatusText="Host Override cleared"; return false;}
                    gs_OverridenHost = sParams[1].toLowerCase();
                    gs_OverrideHostWith = sParams[2];
                    FiddlerObject.StatusText="Connecting to [" + gs_OverrideHostWith + "] for requests to [" + gs_OverridenHost + "]";
                    return true;
                case "urlreplace":
                    if (sParams.Length<3) {gs_ReplaceToken=null; FiddlerObject.StatusText="URL Replacement cleared"; return false;}
                    gs_ReplaceToken = sParams[1];
                    gs_ReplaceTokenWith = sParams[2].Replace(" ", "%20");  // Simple helper
                    FiddlerObject.StatusText="Replacing [" + gs_ReplaceToken + "] in URIs with [" + gs_ReplaceTokenWith + "]";
                    return true;
                case "allbut":
                case "keeponly":
                    if (sParams.Length<2) { FiddlerObject.StatusText="Please specify Content-Type to retain during wipe."; return false;}
                    UI.actSelectSessionsWithResponseHeaderValue("Content-Type", sParams[1]);
                    UI.actRemoveUnselectedSessions();
                    UI.lvSessions.SelectedItems.Clear();
                    FiddlerObject.StatusText="Removed all but Content-Type: " + sParams[1];
                    return true;
                case "stop":
                    UI.actDetachProxy();
                    return true;
                case "start":
                    UI.actAttachProxy();
                    return true;
                case "cls":
                case "clear":
                    UI.actRemoveAllSessions();
                    return true;
                case "g":
                case "go":
                    UI.actResumeAllSessions();
                    return true;
                case "goto":
                    if (sParams.Length != 2) return false;
                    Utilities.LaunchHyperlink("http://www.google.com/search?hl=en&btnI=I%27m+Feeling+Lucky&q=" + Utilities.UrlEncode(sParams[1]));
                    return true;
                case "help":
                    Utilities.LaunchHyperlink("http://fiddler2.com/r/?quickexec");
                    return true;
                case "hide":
                    UI.actMinimizeToTray();
                    return true;
                case "log":
                    FiddlerApplication.Log.LogString((sParams.Length<2) ? "User couldn't think of anything to say..." : sParams[1]);
                    return true;
                case "nuke":
                    UI.actClearWinINETCache();
                    UI.actClearWinINETCookies();
                    return true;
                case "screenshot":
                    UI.actCaptureScreenshot(false);
                    return true;
                case "show":
                    UI.actRestoreWindow();
                    return true;
                case "tail":
                    if (sParams.Length<2) { FiddlerObject.StatusText="Please specify # of sessions to trim the session list to."; return false;}
                    UI.TrimSessionList(int.Parse(sParams[1]));
                    return true;
                case "quit":
                    UI.actExit();
                    return true;
                case "dump":
                    UI.actSelectAll();
                    UI.actSaveSessionsToZip(CONFIG.GetPath("Captures") + "dump.saz");
                    UI.actRemoveAllSessions();
                    FiddlerObject.StatusText = "Dumped all sessions to " + CONFIG.GetPath("Captures") + "dump.saz";
                    return true;
    
                default:
                    if (sAction.StartsWith("http") || sAction.StartsWith("www.")) {
                        System.Diagnostics.Process.Start(sParams[0]);
                        return true;
                    }else if( sParams[0] === "*" ){
                        filter_and_highlight_url = null ;
                        FiddlerObject.StatusText="取消URL高亮";
                    }else{
                        filter_and_highlight_url = sParams[0] ;
                        FiddlerObject.StatusText="将为你高亮包含【" + filter_and_highlight_url + "】的url";
                        // FiddlerObject.StatusText = "Requested ExecAction: '" + sAction + "' not found. Type HELP to learn more.";
                        return true;
                    }
            }
        }
    }
    
    • eruda 和console差不多
        
        
    
    • spy-debugger
      eruda的优点在于,提供了一些工具条,比如加时间戳刷新页面(防缓存),查看设备宽高,像素比等信息,从而加快调试速度;缺点在于:接口请求的数据显示不美观,并且其html元素是静态的,即不显示JS操作DOM生成的页面。vconsole的优缺点刚好相反。二者都有的缺点是:不能调试线上应用(一般不会在线上环境引入调试类的库文件),且无法实时编辑CSS。spy-debugger很强大,eruda和vconsole有的他都有,没有的他也有。不额外加任何文件即可调试线上应用(css,抓包等)。
      使用方式:https://github.com/wuchangming/spy-debugger
    //1、全局安装
    npm install spy-debugger -g
    // 2、启动
    spy-debugger -b false
    // 3、设置手机的HTTP代理
    - Android设置代理步骤:设置 - WLAN - 长按选中网络 - 修改网络 - 高级 - 代理设置 - 手动
    - iOS设置代理步骤:设置 - 无线局域网 - 选中网络 - HTTP代理手动
    // 4、手机安装证书
    手机访问:http://s.xxx
    // 5、开启证书信任(略)
    // 6、手机访问想调试的页面即可
    

    注意点:

    • 不能和vconsole混用(vconsole会触发意外bug)
    • 启动方式:spy-debugger -b false // false代表抓http和https;true只抓https

    以上三种调试方式建议优先使用vconsole,基本能满足需求,有一个问题是有的webview不支持console.log等方法,当在webview里使用时需android或ios小伙伴配合开启console.log开关

    3、实际操作(移动端项目)

    如何将手机端展示项目移到PC端展示,从而用chrome开发者工具来诊断问题?

    • 注意项目初始化代码位置,有时初始化代码是放在ios或安卓相关函数的回调里的,在PC端模拟器没有这个环境,也就不能初始化代码。如果遇到这种情况,只需将初始化代码拿出来,确保得到调用;
    • 注意请求所需header,有的接口需要通过客户端传header或设备相关信息才能拿到数据,若要在pc端看,需要伪造header,这个可以通过用fidder抓包得到。
    • 并不是所有情况都能用PC模拟,如手机端键盘弹起,PC无能为力

    你可能感兴趣的:(H5 代码调试大法)