• 朋友圈、浏览器分享实现


    /**
     * mshare.js
     * 此插件主要作用是在UC和QQ两个主流浏览器
     * 上面触发微信分享到朋友圈或发送给朋友的功能
     * 代码编写过程中 参考:
     * http://mjs.sinaimg.cn/wap/module/share/201501261608/js/addShare.js
     * 此外,JefferyWang的项目对我也有一定启示:
     * https://github.com/JefferyWang/nativeShare.js
     *
     * @revisor  angusfu1126@qq.com
     * @date     2015-07-22
     */
    
    !(function(global) {
        'use strict';
    
        var UA, uc, qq, wx, tc, qqVs, ucVs, os,qqBridgeDone;
    
        UA = navigator.appVersion;
    
        // 是否是 UC 浏览器
        uc = UA.split('UCBrowser/').length > 1  ? 1 : 0;
    
        // 判断 qq 浏览器
        // 然而qq浏览器分高低版本   2代表高版本  1代表低版本
        qq = UA.split('MQQBrowser/').length > 1 ? 2 : 0;
    
        // 是否是微信
        wx = ((UA.match(/MicroMessenger/i)) && (UA.match(/MicroMessenger/i).toString().toLowerCase() == 'micromessenger'));
    
        // 浏览器版本
        qqVs = qq ? parseFloat(UA.split('MQQBrowser/')[1]) : 0;
        ucVs = uc ?  parseFloat(UA.split('UCBrowser/')[1]) : 0;
        
        //获取操作系统信息  iPhone(1)  Android(2)
        os = (function () {
            var ua = navigator.userAgent;
    
            if (/iphone|ipod/i.test(ua)) {
                return 1;
            } else if(/android/i.test(ua)){
                return 2;
            } else {
                return 0;
            }
        }());
    
        // qq浏览器下面 是否加载好了相应的api文件
        qqBridgeDone = false;
    
        // 进一步细化版本和平台判断
        // 参考: https://github.com/JefferyWang/nativeShare.js
        // http://mjs.sinaimg.cn/wap/module/share/201501261608/js/addShare.js
        if ((qq && qqVs < 5.4 && os == 1) || (qq && qqVs < 5.3 && os == 1)) {
            qq = 0;
        } else {
            if (qq && qqVs < 5.4 && os == 2) {
                qq = 1;
            } else {
                if (uc && ( (ucVs < 10.2 && os == 1) || (ucVs < 9.7 && os == 2) )) {
                    uc = 0;
                }
            }
        }
    
        /**
         * qq浏览器下面 根据不同版本 加载对应的bridge
         * @method loadqqApi
         * @param  {Function} cb 回调函数
         */
        function loadqqApi(cb) {
            if (!qq) { // qq == 0 
                return cb && cb();
            }
    
            var qqApiScript = document.createElement('script');
            //需要等加载过qq的接口文档之后,再去初始化分享组件
            qqApiScript.onload = function () {cb && cb();};
            qqApiScript.onerror = function () {};
            // qq == 1 低版本
            // qq == 2 高版本
            qqApiScript.src = (qq == 1 ) ? 'http://3gimg.qq.com/html5/js/qb.js' : 'http://jsapi.qq.com/get?api=app.share';
    
            document.body.appendChild(qqApiScript);
        }
    
    
        /**
         * UC浏览器分享
         * @method ucShare
         */
        function ucShare(config) {
            // ['title', 'content', 'url', 'platform', 'disablePlatform', 'source', 'htmlID']
            // 关于platform
            // ios: kWeixin || kWeixinFriend;
            // android: WechatFriends || WechatTimeline
            // uc 分享会直接使用截图
            
            var platform = '', shareInfo;
    
            // 指定了分享类型
            if (config.type) {
                if (os == 2) {
                    platform = config.type == 1 ? 'WechatTimeline' : 'WechatFriends';
                } else if (os == 1) {
                    platform = config.type == 1 ? 'kWeixinFriend' : 'kWeixin';
                }
            }
    
            shareInfo = [ config.title, config.desc, config.url, platform, '', '', '' ];
    
            // android 
            if (window.ucweb) {
                ucweb.startRequest && ucweb.startRequest('shell.page_share', shareInfo);
            }
            // ios
            else if (window.ucbrowser) {
                ucbrowser.web_share && ucbrowser.web_share.apply(null, shareInfo);
            }
    
        };
        
    
        /**
         * qq浏览器分享函数
         * @method qqShare
         */
        function qqShare(config) {
            var type = config.type;
    
            //微信好友1, 微信朋友圈8
            type = type ? ((type == 1) ? 8 : 1) : ''; 
    
            var share = function () {
                var shareInfo = {
                    'url': config.url,
                    'title': config.title,
                    'description': config.desc,
                    'img_url': config.img,
                    'img_title': config.title,
                    'to_app': type,
                    'cus_txt': ''
                };
    
                if (window.browser) {
                    browser.app && browser.app.share(shareInfo);
                } else if (window.qb) {
                    qb.share && qb.share(shareInfo);
                }
            };
    
            if (qqBridgeDone) {
                share();
            } else {
                loadqqApi(share);
            }
        };
    
        /**
         * 对外暴露的接口函数
         * @method mShare
         * @param  {Object} config 配置对象  参数见示例
         *     var config = {
         *          title : 'Lorem ipsum dolor sit.'
         *        , url   : 'http://m.ly.com'
         *        , desc  : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat inventore minima voluptates.'
         *        , img   : 'http://img1.40017.cn/cn/s/c/2015/loading.gif'
         *        , type  : type // 1 ==> 朋友圈  2 ==> 朋友  0 ==> 直接弹出原生
         *     }
         */
        function mShare(config) {
            this.check = function (succssFn, wxFn, failFn) {
                if (uc) {
                    succssFn();
                } else if (qq && !wx) {
                    succssFn();
                } else if (wx) {
                    wxFn();
                } else {
                    failFn();
                }
            }
            this.config = config;
            this.init = function (type) {
                if (typeof type != 'undefined') this.config.type = type;
                try {
                    if (uc) {
                        ucShare(this.config);
                    } else if (qq && !wx) {
                        qqShare(this.config);
                    }
                } catch (e) {}
            }
        }
        
        // 预加载 qq bridge
        loadqqApi(function () {
            qqBridgeDone = true;
        });
    
        // 方法暴露给全局变量
        global.mShare = mShare;
    
    })(this);
    //=====================这是分割线=====================================
    <div class="sharePage">
        <div class="sharePage_background"></div>
        <div class="sharePage_bottom">
            <div class="share_mode">
                <div class="share_mode_header">分享至</div>
                <div class="share_mode_content">
                    <ul class="clearfix">
                        <li class="WeChat mshare" mshare="2">
                            <span></span>
                            <i>微信</i>
                        </li>
                        <li class="moments mshare" mshare="1">
                            <span></span>
                            <i>朋友圈</i>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="share_cancel">
                取消
            </div>
        </div>
        <div class="sharePage_arrow">
            <span></span>
            <p>点击微信右上角按钮进行分享</p>
        </div>
    </div>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="/mobile/js/lib/jquery-2.0.3.min.js"></script>
    <script src="/mobile/js/lib/mshare.js"></script>
    <script>
        var mshare = new mShare({
              title : '{{shareTitle}}',
              url   : '{{shareUrl}}',
              desc  : '{{shareDesc}}',
              img   : '{{sharePic}}'
        });
        
        mshare.check(
            function () {//支持原生分享
                browserShow ();
                $('.mshare').click(function () {
                    // 1 ==> 朋友圈  2 ==> 朋友  0 ==> 直接弹出原生
                    mshare.init(+$(this).attr('mshare'));
                });
            },
            function () {//微信中支持微信分享
                WeChatShow ();
                wx.config({
                    debug: false,
                    appId: "{{options['appid']}}",
                    timestamp: "{{options['timestamp']}}",
                    nonceStr: "{{options['nonceStr']}}",
                    signature: "{{options['signature']}}",
                    jsApiList: [
                        'checkJsApi',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                      ]
                });
                wx.ready(function(){
                    wx.checkJsApi({
                        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
                        success: function(res) {
                            //alert("检测结果" + res.errMsg);
                            // 以键值对的形式返回,可用的api值true,不可用为false
                            // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                        }
                    });
    
                    wx.onMenuShareTimeline({
                        title: '{{shareTitle}}', // 分享标题
                        link: '{{shareUrl}}', // 分享链接
                        imgUrl: '{{sharePic}}', // 分享图标
                        success: function () {
                            //alert("分享到微信朋友圈成功");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            //alert("取消分享");
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareAppMessage({
                        title: '{{shareTitle}}', // 分享标题
                        link: '{{shareUrl}}', // 分享链接
                        imgUrl: '{{sharePic}}', // 分享图标
                        desc: "{{shareDesc}}", // 分享描述
                        type: 'link', // 分享类型,music、video或link,不填默认为link
                        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                        success: function () {
                            //alert("分享到微信好友成功");
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                            //alert("取消分享")
                        }
                    });
                    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
                });
    
                wx.error(function(res){
                    //alert('error');
                    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
                });
            },
            function () {//不支持分享
                shareHide();
            }
        );
        
        //在浏览器中打开
        function browserShow () {
            //点击分享按钮
            $('.share_button').show();
            $('.share_button').click(function () {
                $('.sharePage').addClass('sharePage_active');
                $('.sharePage_bottom').animate({
                    bottom:0
                },300);
            });
            //点击取消按钮
            $('.share_cancel').click(function () {
                $('.sharePage_bottom').animate({
                    bottom:-$('.sharePage_bottom').height()+'px'
                },300,function () {
                    $('.sharePage').removeClass('sharePage_active');
                });
            });
            //点击黑色背景,整个分享页面消失
            $('.sharePage_background').click(function () {
                $('.sharePage_bottom').animate({
                    bottom:-$('.sharePage_bottom').height()+'px'
                },300,function () {
                    $('.sharePage').removeClass('sharePage_active');
                });
            });
        }
        //在微信中打开
        function WeChatShow () {
            //点击分享按钮
            $('.share_button').show();
            $('.share_button').click(function () {
                $('.sharePage').addClass('sharePage_active');
                $('.sharePage_arrow').addClass('sharePage_arrow_active');
            });
            //点击黑色背景整个分享页面消失
            $('.sharePage_arrow').click(function () {
                $('.sharePage').removeClass('sharePage_active');
                $('.sharePage_arrow').removeClass('sharePage_arrow_active');
            });
        }
        
        function shareHide() {
            $('.share_button').hide();
        }
    </script>
    
    作者:beijing_beijing
    链接:https://www.jianshu.com/p/3d6503c68474
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    Android Studio的git功能的使用介绍
    如何用Android Studio同时使用SVN和Git管理项目
    【.NET深呼吸】动态类型(扩充篇)
    【.net深呼吸】动态类型(高级篇)
    【.net深呼吸】动态类型(娱乐篇)
    VS 2015相当不错的功能:C#交互窗口
    计算照片的面积(WPF篇)
    计算照片的面积(UWP篇)
    【Win 10应用开发】把文件嵌入到XML文档
    【.NET深呼吸】基础:自定义类型转换
  • 原文地址:https://www.cnblogs.com/lxwphp/p/9719433.html
Copyright © 2020-2023  润新知