您现在的位置:首页 >> 前端 >> 内容

微信浏览器点击选择图片报错 WeiXinJSbridge is not defined如何解决?

时间:2018/3/31 11:41:18 点击:

  核心提示:最近做一个h5界面,在个人中心需要有个用户头像修改的功能,然后就用了input type=file,在手机浏览器运行很正常,但是在微信浏览器就出现了异常,用window.onerror输出看到报错:W...

最近做一个h5界面,在个人中心需要有个用户头像修改的功能,然后就用了<input type="file">,

在手机浏览器运行很正常,但是在微信浏览器就出现了异常,用window.onerror输出看到报错:WeiXinJSbridge is not defined。

一脸懵逼啊,根本没有用到WeiXinJSbridge,然后在万能的百度上搜了一下,这是微信浏览器内置的类,在微信浏览器中会初始化,没初始化后用就会报这个错。但是基本上都是说微信支付的问题。好吧,我虽然没用到,但是问题出来了(我真不知道一个图片修改哪里用到了WeiXinJSbridge,如有知道的大神麻烦留言指点,先谢过了!),那就得解决吧。

然后我就想,既然是没初始化完成报错,而且只是选择图片的时候报错,那么我在微信浏览器就先判断WeiXinJSbridge是否初始化了呗。做了如下几步,问题基本解决:

1.将<input type="file">默认设为不可用,即<input type="file" disabled="disabled">;

2.判断是否是微信浏览器

                        /** 
             * 此方法判断是否是在微信浏览器中 
             */  
            function isWeixin() {  
                var WxObj = window.navigator.userAgent.toLowerCase();  
                if(WxObj.match(/microMessenger/i) == 'micromessenger') {  
                    return true;  
                } else {  
                    return false;  
                }  
  

3.如果是微信浏览器就检测是否初始化完成,或者设置初始化完成的监听方法/非微信浏览器将input设为可用

                            if(isWeixin()) {  
                    if(typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {  
                        $("input[id=img]").removeAttr("disabled");  
                    } else {  
                        document.addEventListener("WeixinJSBridgeReady", function() {  
                            $("input[id=img]").removeAttr("disabled");  
                        }, false);  
                    }  
  
                } else {  
                    $("input[id=img]").removeAttr("disabled");  
                }  

4.然后保存,运行正常了

测试代码如下:

<!DOCTYPE html>  
<html>  
  
    <head>  
        <meta charset="UTF-8">  
        <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">  
        <meta name="format-detection" content="telephone=no, email=no">  
        <title>个人中心</title>  
        <script type="text/javascript">  
            (function(win) {  
                var doc = win.document;  
                var html = doc.documentElement;  
                // defaut 1080px  
                var baseWidth = 1080;  
                var grids = baseWidth / 100,  
                    resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize',  
                    recalc = function() {  
                        var clientWidth = html.clientWidth || 375; // default to 375 if can't get device-width  
                        html.style.fontSize = clientWidth / grids + 'px';  
                    };  
                win.addEventListener(resizeEvt, recalc, false);  
                doc.addEventListener('DOMContentLoaded', recalc, false);  
                recalc();  
            })(window);  
        </script>  
        <script src="js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>  
        <style>  
            body {  
                background: #f2f2f2  
            }  
              
            .user {  
                background: #fff;  
                text-align: left;  
                padding: .6rem 0  
            }  
              
            .user-avatar {  
                display: inline-block;  
                width: 1.15rem;  
                height: 1.15rem;  
                border-radius: 50%;  
                overflow: hidden;  
                vertical-align: middle;  
                margin-left: .6rem  
            }  
              
            .user-avatar img {  
                display: block;  
                width: 100%;  
                height: 100%  
            }  
              
            .user-name {  
                font-size: .42rem;  
                color: #323232  
            }  
              
            .user-nickname {  
                font-size: .42rem;  
                color: #323232;  
                line-height: 1;  
                display: inline-block;  
                margin-left: .34rem;  
                vertical-align: middle  
            }  
              
            .input-upload-image {  
                width: 100%;  
                height: 100%;  
                display: block;  
                z-index: 1;  
                border: none;  
                -webkit-opacity: 0;  
                opacity: 0;  
            }  
              
            .user-avatar img {  
                z-index: 2;  
                margin-top: -1.15rem;  
            }  
        </style>  
    </head>  
  
    <body>  
        <p class="user">  
            <p class="user-avatar">  
                <input type="file" disabled="disabled" accept="image/*" multiple="multiple" id="img" class="input-upload-image" />  
                <img src="img/grzx_avatar-460e304cd2.png" alt="">  
            </p>  
            <p class="user-nickname" style="min-width: 80px;">个人昵称</p>  
        </p>  
  
        <script>  
            var b64;  
            var dataUrl;  
            var file = null;  
            var result1 = '',  
                result2 = '',  
                result3 = '',  
                result4 = '',  
                result5 = '',  
                result6 = '';  
  
            document.getElementById("img").addEventListener('change', function(ev) {  
                ev.stopPropagation();  
                var thisimg = document.getElementById("img");  
                var reader = new FileReader();  
                reader.onload = function(e) {  
                    var compressImg = compress(this.result, fileSize, function(base64Str) {  
  
                        thisimg.src = base64Str;  
                          
                        uploadimg(function(res) {  
                            if(res != null) {  
                                $(thisimg).parent().find("img").attr("src", base64Str);  
                            }  
                        });  
                    });  
                    b64 = e.target.result;  
  
                };  
  
                reader.readAsDataURL(this.files[0]);  
  
                result1 = this.files[0].size + ' Bytes';  
                file = this.files[0];  
                var fileSize = Math.round(this.files[0].size / 1024 / 1024);  
  
            }, false);  
                  
            /**  
             * 上传图片  
             * @param {Object} callbc  
             */  
            function uploadimg(callbc) {  
                if(file != null) {  
  
                    var xmlhttp = null;  
                    var formData = new FormData(); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数    
  
                    formData.append("imgfile", convertBase64UrlToBlob(dataUrl));  
                    formData.append("fileType", ".png");  
                    formData.append("uid", 1);  
  
                    var f = convertBase64UrlToBlob(dataUrl);  
  
                    var url = "https://xxxxxx/uploadImg.php";//你的上传图片的服务地址  
  
                    if(window.XMLHttpRequest) {  
                        xmlhttp = new XMLHttpRequest();  
                    } else if(window.ActiveXObject) {  
                        xmlhttp = new ActiveXObject();  
                    }  
  
                    xmlhttp.open("POST", url, true);  
                    xmlhttp.send(formData);  
                    xmlhttp.onload = function(e) {  
  
                        if(this.status == 200) {  
  
                            var obj = eval("(" + this.responseText + ")");  
                            callbc(obj);  
                              
                        }  
                    };  
                } else {  
                    alert("请点击头像选择图片");  
                }  
            }  
  
            var compress = function(res, fileSize, callback) {  
                var result2, result3, result4, result5;  
                var img = new Image(),  
                    maxW = 600; //设置最大宽度  
  
                img.onload = function() {  
                    var cvs = document.createElement('canvas'),  
                        ctx = cvs.getContext('2d');  
                    result2 = img.width;  
                    result3 = img.height;  
  
                    if(result3 > 600) {  
                        img.width *= 600 / img.height;  
                        img.height = 600;  
                    } else {  
  
                    }  
  
                    if(img.width > maxW) {  
                        img.height *= maxW / img.width;  
                        img.width = maxW;  
                    }  
  
                    cvs.width = img.width;  
                    cvs.height = img.height;  
  
                    result4 = cvs.width;  
                    result5 = cvs.height;  
  
                    ctx.clearRect(0, 0, cvs.width, cvs.height);  
                    ctx.drawImage(img, 0, 0, img.width, img.height);  
  
                    var compressRate = getCompressRate(0.8, fileSize);  
  
                    dataUrl = cvs.toDataURL('image/*', compressRate);  
  
                    callback(dataUrl);  
                };  
  
                img.src = res;  
            };  
  
            function getCompressRate(allowMaxSize, fileSize) { //计算压缩比率,size单位为MB  
  
                var compressRate = 1;  
  
                if(fileSize >= 1) {  
                    compressRate = 0.6;  
                } else if(fileSize > 0.2 && fileSize < 1) {  
                    compressRate = 0.8;  
                } else {  
                    compressRate = 0.9;  
                }  
                result6 = compressRate;  
  
                return compressRate;  
            }  
  
            /**    
             * 将以base64的图片url数据转换为Blob    
             * @param urlData    
             *            用url方式表示的base64图片数据    
             */  
            function convertBase64UrlToBlob(urlData) {  
  
                var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte    
  
                //处理异常,将ascii码小于0的转换为大于0    
                var ab = new ArrayBuffer(bytes.length);  
                var ia = new Uint8Array(ab);  
                for(var i = 0; i < bytes.length; i++) {  
                    ia[i] = bytes.charCodeAt(i);  
                }  
                return new Blob([ab], {  
                    type: 'image/png'  
                });  
            }  
        </script>  
  
        <script>  
            setCanChangePic();  
  
            /**  
             * 设置input选择图片可用  
             */  
            function setCanChangePic() {  
  
                if(isWeixin()) {  
                    if(typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {  
                        $("input[id=img]").removeAttr("disabled");  
                    } else {  
                        document.addEventListener("WeixinJSBridgeReady", function() {  
                            $("input[id=img]").removeAttr("disabled");  
                        }, false);  
                    }  
  
                } else {  
                    $("input[id=img]").removeAttr("disabled");  
                }  
  
            }  
            /**  
             * 此方法判断是否是在微信浏览器中  
             */  
            function isWeixin() {  
                var WxObj = window.navigator.userAgent.toLowerCase();  
                if(WxObj.match(/microMessenger/i) == 'micromessenger') {  
                    return true;  
                } else {  
                    return false;  
                }  
  
            }  
        </script>  
  
    </body>  
  
</html>  

作者:网络 来源:u012962759