[Original] [WeChat development] WeChat sharing

Since the global WeChat sharing function is used in the project, a small plug-in is written.

1. Document introduction and use

    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" charset="utf-8" type="text/javascript"></script>
    <script type="text/javascript" src="js/common/wechat-share.js"></script>
    <script>
        // Share 
        $.wechatShare({
             // Load the DOM HTMLElement of the page 
            pageHtmlElement: document.body,
        });
    </script>

 

2. Plug-in source code

/**
 * jQuery wechat share v1.0
 *
 * Description: If the title is not captured, use the default title, default description, default image, and default shared link
 *
 * Input parameters:
 * 0. pageHtmlElement Loaded page HtmlElement
 *
 * @author likl
 */
(function($) {
    
    // Default parameters 
    $.paramsDefault = {
        css_wechat_background: ".wechat_share_img", // Class name of the background image to be captured, if you want to get the background image, you need to manually set 
        css_wechat_img: "div.page-content>div:not('.navbarpages') img" , // the img tag selector to be grabbed 
        css_wechat_title: ".wechat_share_title", // the class name of the title to be grabbed 
        css_wechat_desc: ".wechat_share_desc", // the class name of the title to be grabbed 
        wxShareKeyword: " from=singlemessage", // Cannot be modified, wechat shares key logos to prevent wechat from removing the link after #, which will only lead to the problem of entering the home page 
        splitChar: "#!", //modify according to the needs of the project , currently I use framework7, so Configure # here! (mainly to prevent the problem that the single-page application link cannot take effect when WeChat sharing) 
        defaultTitle: "New life on the cloud",Default description 
        defaultWechatImgUrl: "/resource/kechuang/images/index/logo-round-white.png", // default picture 
        defaultUrl: "/index.hx", // default link 
        shareTitle: "", // finally shared Title 
        shareDesc: "", // Description of the final sharing 
        shareWechatImgUrl: "", // The final sharing image 
        shareUrl: "", // The final sharing link 
        pageHtmlElement: "" // Input: DOM HTMLElement of the loaded page 
    };

    /**
     * share function
     * Input parameter: pageHtmlElement
     */
    $.wechatShare = function(options) {
        var opts = $.extend(jQuery.paramsDefault, options);
        
        var wxShareKeyword = opts.wxShareKeyword;
        var splitChar = opts.splitChar;
        var pageHtmlElement = opts.pageHtmlElement;//载入页面的DOM HTMLElement
        
        var requestUrl = location.href;
        console.log( "requestUrl:" + requestUrl);
         
     // Request the server to obtain configuration information and call WeChat config for registration $.ajax({ type:
"POST", data: {"requestUrl": requestUrl.split(splitChar)[0]}, async: true, url: "jssdkconfig.hx" , // Configure the request connection of your own server and get the jssdk configuration information dataType: "json" , success: function (data) { if (data.status) { // Inject WeChat permission verification configuration wx.config({ debug: false , // Enable the debug mode, the return values ​​of all the apis called will be alerted on the client side, if you want to view the incoming parameters, you can open it on the pc side, and the parameter information will be printed out through the log, only on the pc side will print. appId: data.attr.appId, // required, the unique identifier of the official account timestamp: data.attr.timestamp, // required, the timestamp to generate the signature nonceStr: data.attr.nonceStr, // required, generated Signature random string signature: data.attr.signature, // required, signature jsApiList: ["onMenuShareTimeline","onMenuShareAppMessage"] // required, a list of JS interfaces to be used, all JS interfaces are listed in Appendix 2 }) ; } else { console.log(data.info); } } }); // Get title and content var content = $.grabContent({pageHtmlElement: pageHtmlElement}); opts = $.extend(opts, content); // Union integration content // Share interface definition wx.ready( function () { // Share to Moments wx.onMenuShareTimeline({ title: opts.shareTitle, // share title link: opts.shareUrl, // share link, the link domain name or path must be consistent with the public account JS security domain name corresponding to the current page imgUrl: opts.shareWechatImgUrl, // share icon success: function () { // Callback function executed after user confirms sharing }, cancel: function () { // The callback function executed after the user cancels the sharing } }); // Send to WeChat friends wx.onMenuShareAppMessage({ title: opts.shareTitle, // share title desc: opts.shareDesc, // share description link: opts.shareUrl, // share link, the link domain name or path must be consistent with the public account JS security domain name corresponding to the current page imgUrl: opts.shareWechatImgUrl, // Share icon type: 'link', // Share type, music, video or link, if not filled, the default is link dataUrl: '', // If the type is music or video, a data link should be provided, The default is empty success: function () { // The callback function executed after the user confirms the sharing }, cancel: function () { // The callback function executed after the user cancels the sharing } }); wx.error(function(res){ console.log("js-sdk -- res:" + res); }); }); }; /** * Grab the title and description */ $.grabContent = function (options) { var pageHtmlElement = options.pageHtmlElement; // Load the DOM HTMLElement of the page // Title var title = $(pageHtmlElement).find($.paramsDefault.css_wechat_title).html(); // Title console.log("title:" + title); // If the title is empty, the default title is used and description if (title == null || $.trim(title) == "" ){ // use default var defaultWechatImgUrl = location.protocol + "//" + location.host + $.paramsDefault.defaultWechatImgUrl; var shareUrl = location.protocol + "//" + location.host + $.paramsDefault.defaultUrl; return{shareTitle: $.paramsDefault.defaultTitle, shareDesc: $.paramsDefault.defaultDesc, shareWechatImgUrl: defaultWechatImgUrl, shareUrl: shareUrl}; } // description var desc = parseHtml($(pageHtmlElement).find($.paramsDefault.css_wechat_desc)); if (title == null || $.trim(title) == "" ){ // use default desc = $ .paramsDefault.defaultDesc; } else { // 20 characters if (desc.length > 20 ){ desc = desc.substring(0, 20) + "..."; } } console.log( "Shared desc:" + desc); // Get the shared image var wechatImgUrl = $.grabImageUrl({pageHtmlElement: pageHtmlElement}); console.log( "Final wechatImgUrl:" + wechatImgUrl); // Get dynamic share link var requestUrl = window.location.href; var prefix = requestUrl.split($.paramsDefault.splitChar)[0 ]; if (prefix.indexOf($.paramsDefault.wxShareKeyword) <= 0 ){ prefix = prefix + "?" + $.paramsDefault.wxShareKeyword; // Add share key parameters } var last = requestUrl.split($.paramsDefault.splitChar)[1]; // Content after # or #! // final Shared link... requestUrl = prefix + $.paramsDefault.splitChar + last; console.log( "The final shared link:" + requestUrl); return {shareTitle: title, shareDesc: desc, shareWechatImgUrl: wechatImgUrl, shareUrl: requestUrl}; }; /** * Grab pictures to share * Input parameters: pageHtmlElement, loaded page HtmlElement */ $.grabImageUrl = function(options) { var opts = $.extend(jQuery.paramsDefault, options); var pageHtmlElement = opts.pageHtmlElement; // Load the DOM HTMLElement of the page // Grab the background image var wechatImgs = $(pageHtmlElement).find(opts.css_wechat_background); var wechatImgUrl = wechatImgs.length > 0 ? $(wechatImgs[0]).css("backgroundImage") : "" ; console.log( "wechat_img:" + wechatImgUrl); if (wechatImgUrl == null || $.trim(wechatImgUrl) == "" ){ // If the background image is preset, then take the img image var imgs = $ (pageHtmlElement).find(opts.css_wechat_img); if (imgs.length > 0 ){ wechatImgUrl = $(imgs[0]).attr("src"); console.log( "The obtained img image url:" + wechatImgUrl); } } else { // If the obtained background image, there are two cases: url(aaa.jpg) or url("aaa.jpg") wechatImgUrl = wechatImgUrl.split("(")[1].split(") ")[0 ]; if (wechatImgUrl.split("\"").length > 1 ){ wechatImgUrl = wechatImgUrl.split("\"")[1]; } } // If no image is captured, take the default image if (isEmpty(wechatImgUrl)){ wechatImgUrl = opts.defaultWechatImgUrl; } // Add domain name to background image if (!/^http:\/\/|https:\/\// .test(wechatImgUrl)){ wechatImgUrl = location.protocol + "//" + location.host + wechatImgUrl; } console.log( "The final shared image url:" + wechatImgUrl); // Return the picture return wechatImgUrl; }; })(jQuery);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168453&siteId=291194637