js实现微信分享给好友功能

发布时间:2020-02-21编辑:脚本学堂
本文介绍了js实现的微信分享给好友的功能代码,有需要的朋友参考下。

手机微信里,分享给好友时,在当前页面指定分享的URL和图片,用js代码实现的,大家做个参考。

例子,微信分享给好友。
 

复制代码 代码示例:
function share_scene(link, scene_type){ 
    var extargs = ""; 
    if (tid != ""){//gdt traceid 
        extargs = "tid=" + tid + "&aid=" + 54;//share must be 54 
    } 
    var queryStr = link.split('?')[1] || ''; 
        queryStr = queryStr.split('#')[0]; 
    if( queryStr == '' ){ 
        return; 
    } 
     
    var queryarr = [queryStr, 'scene='+scene_type]; 
    (extargs != "") && (queryarr.push(extargs)); 
    queryStr = queryarr.join('&'); 
 
    return link.split('?')[0] + '?' + queryStr + '#' + (link.split('#')[1]||''); 
}
 
function  onBridgeReady(){ 
 // 发送给好友;  
    //安卓分享时会调用此函数 
    WeixinJSBridge.on('menu:share:appmessage', function(argv){ 
                WeixinJSBridge.invoke('sendAppMessage',{ 
                                      "appid"      : appId, 
                                      "img_url"    : imgUrl, 
                                      "img_width"  : "640", 
                                      "img_height" : "640", 
                                      "link"       : share_scene(link, 1), 
                                      "desc"       : desc, 
                                      "title"      : title 
                }, function(res) { 
  
                }); 
    }); // www.jb200.com 
 
    // 新的接口 
    //苹果分享时会调用此函数 
    WeixinJSBridge.on('menu:general:share', function(argv){ 
        var scene = 0; 
        switch(argv.shareTo){ 
            case 'friend'  : scene = 1; break
            case 'timeline': scene = 2; break; 
            case 'weibo'   : scene = 3; break; 
        } 
 
            argv.generalShare({ 
                                "appid"      : appId, 
                                "img_url"    : imgUrl, 
                                "img_width"  : "640", 
                                "img_height" : "640", 
                                "link"       : share_scene(link,scene), 
                                "desc"       : desc, 
                                "title"      : title 
            }, function(res){ 
 
            }); 
    }); 
}  
 if (typeof WeixinJSBridge == "undefined"){ 
         if( document.addEventListener ){ 
             document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); 
         }else if (document.attachEvent){ 
             document.attachEvent('WeixinJSBridgeReady', onBridgeReady);  
             document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); 
         } 
     }else{ 
         onBridgeReady(); 
     }