search
HomeWeb Front-endJS Tutorialjs implements WeChat sharing code_javascript skills

Usually when I want to share a page with friends through WeChat, the title and description displayed are not what I want. I checked some information and found that it is controlled through js
The display effect is as follows:

Title, description, and shared pictures are all controlled by js.
The js code is as follows

<script>
    var dataForWeixin = {
      appId: "",
      MsgImg: "Christmas/201012189457639.gif",//显示图片
      TLImg: "Christmas/201012189457639.gif",//显示图片
      url: "Christmas/6.html&#63;stra=!u738B!u4F1F",//跳转地址
      title: "将我的思念和祝福送给您,颐养源祝大家圣诞快乐",//标题内容
      desc: "将我的思念和祝福送给您,颐养源祝大家圣诞快乐",//描述内容
      fakeid: "",
      callback: function () { }
    };
    (function () {
      var onBridgeReady = function () {
        WeixinJSBridge.on('menu:share:appmessage', function (argv) {
          WeixinJSBridge.invoke('sendAppMessage', {
            "appid": dataForWeixin.appId,
            "img_url": dataForWeixin.MsgImg,
            "img_width": "120",
            "img_height": "120",
            "link": dataForWeixin.url,
            "desc": dataForWeixin.desc,
            "title": dataForWeixin.title
          }, function (res) { (dataForWeixin.callback)(); });
        });
        WeixinJSBridge.on('menu:share:timeline', function (argv) {
          (dataForWeixin.callback)();
          WeixinJSBridge.invoke('shareTimeline', {
            "img_url": dataForWeixin.TLImg,
            "img_width": "120",
            "img_height": "120",
            "link": dataForWeixin.url,
            "desc": dataForWeixin.desc,
            "title": dataForWeixin.title
          }, function (res) { });
        });
        WeixinJSBridge.on('menu:share:weibo', function (argv) {
          WeixinJSBridge.invoke('shareWeibo', {
            "content": dataForWeixin.title,
            "url": dataForWeixin.url
          }, function (res) { (dataForWeixin.callback)(); });
        });
        WeixinJSBridge.on('menu:share:facebook', function (argv) {
          (dataForWeixin.callback)();
          WeixinJSBridge.invoke('shareFB', {
            "img_url": dataForWeixin.TLImg,
            "img_width": "120",
            "img_height": "120",
            "link": dataForWeixin.url,
            "desc": dataForWeixin.desc,
            "title": dataForWeixin.title
          }, function (res) { });
        });
      };
 
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
      }
    })();
</script>

Another WeChat sharing js code:

/**!
 * 微信内置浏览器的Javascript API,功能包括:
 *
 * 1、分享到微信朋友圈
 * 2、分享给微信好友
 * 3、分享到腾讯微博
 * 4、新的分享接口,包含朋友圈、好友、微博的分享(for iOS)
 * 5、隐藏/显示右上角的菜单入口
 * 6、隐藏/显示底部浏览器工具栏
 * 7、获取当前的网络状态
 * 8、调起微信客户端的图片播放组件
 * 9、关闭公众平台Web页面
 */
var WeixinApi = (function () {

  "use strict";

  /**
   * 分享到微信朋友圈
   * @param    {Object}  data    待分享的信息
   * @p-config  {String}  appId   公众平台的appId(服务号可用)
   * @p-config  {String}  imgUrl   图片地址
   * @p-config  {String}  link    链接地址
   * @p-config  {String}  desc    描述
   * @p-config  {String}  title   分享的标题
   *
   * @param    {Object}  callbacks 相关回调方法
   * @p-config  {Boolean}  async          ready方法是否需要异步执行,默认false
   * @p-config  {Function} ready(argv)       就绪状态
   * @p-config  {Function} dataLoaded(data)    数据加载完成后调用,async为true时有用,也可以为空
   * @p-config  {Function} cancel(resp)  取消
   * @p-config  {Function} fail(resp)   失败
   * @p-config  {Function} confirm(resp)  成功
   * @p-config  {Function} all(resp)    无论成功失败都会执行的回调
   */
  function weixinShareTimeline(data, callbacks) {
    callbacks = callbacks || {};
    var shareTimeline = function (theData) {
      WeixinJSBridge.invoke('shareTimeline', {
        "appid":theData.appId &#63; theData.appId : '',
        "img_url":theData.imgUrl,
        "link":theData.link,
        "desc":theData.title,
        "title":theData.desc, // 注意这里要分享出去的内容是desc
        "img_width":"640",
        "img_height":"640"
      }, function (resp) {
        switch (resp.err_msg) {
          // share_timeline:cancel 用户取消
          case 'share_timeline:cancel':
            callbacks.cancel && callbacks.cancel(resp);
            break;
          // share_timeline:confirm 发送成功
          case 'share_timeline:confirm':
          case 'share_timeline:ok':
            callbacks.confirm && callbacks.confirm(resp);
            break;
          // share_timeline:fail 发送失败
          case 'share_timeline:fail':
          default:
            callbacks.fail && callbacks.fail(resp);
            break;
        }
        // 无论成功失败都会执行的回调
        callbacks.all && callbacks.all(resp);
      });
    };
    WeixinJSBridge.on('menu:share:timeline', function (argv) {
      if (callbacks.async && callbacks.ready) {
        window["_wx_loadedCb_"] = callbacks.dataLoaded || new Function();
        if(window["_wx_loadedCb_"].toString().indexOf("_wx_loadedCb_") > 0) {
          window["_wx_loadedCb_"] = new Function();
        }
        callbacks.dataLoaded = function (newData) {
          window["_wx_loadedCb_"](newData);
          shareTimeline(newData);
        };
        // 然后就绪
        callbacks.ready && callbacks.ready(argv);
      } else {
        // 就绪状态
        callbacks.ready && callbacks.ready(argv);
        shareTimeline(data);
      }
    });
  }

  /**
   * 发送给微信上的好友
   * @param    {Object}  data    待分享的信息
   * @p-config  {String}  appId   公众平台的appId(服务号可用)
   * @p-config  {String}  imgUrl   图片地址
   * @p-config  {String}  link    链接地址
   * @p-config  {String}  desc    描述
   * @p-config  {String}  title   分享的标题
   *
   * @param    {Object}  callbacks 相关回调方法
   * @p-config  {Boolean}  async          ready方法是否需要异步执行,默认false
   * @p-config  {Function} ready(argv)       就绪状态
   * @p-config  {Function} dataLoaded(data)    数据加载完成后调用,async为true时有用,也可以为空
   * @p-config  {Function} cancel(resp)  取消
   * @p-config  {Function} fail(resp)   失败
   * @p-config  {Function} confirm(resp)  成功
   * @p-config  {Function} all(resp)    无论成功失败都会执行的回调
   */
  function weixinSendAppMessage(data, callbacks) {
    callbacks = callbacks || {};
    var sendAppMessage = function (theData) {
      WeixinJSBridge.invoke('sendAppMessage', {
        "appid":theData.appId &#63; theData.appId : '',
        "img_url":theData.imgUrl,
        "link":theData.link,
        "desc":theData.desc,
        "title":theData.title,
        "img_width":"640",
        "img_height":"640"
      }, function (resp) {
        switch (resp.err_msg) {
          // send_app_msg:cancel 用户取消
          case 'send_app_msg:cancel':
            callbacks.cancel && callbacks.cancel(resp);
            break;
          // send_app_msg:confirm 发送成功
          case 'send_app_msg:confirm':
          case 'send_app_msg:ok':
            callbacks.confirm && callbacks.confirm(resp);
            break;
          // send_app_msg:fail 发送失败
          case 'send_app_msg:fail':
          default:
            callbacks.fail && callbacks.fail(resp);
            break;
        }
        // 无论成功失败都会执行的回调
        callbacks.all && callbacks.all(resp);
      });
    };
    WeixinJSBridge.on('menu:share:appmessage', function (argv) {
      if (callbacks.async && callbacks.ready) {
        window["_wx_loadedCb_"] = callbacks.dataLoaded || new Function();
        if(window["_wx_loadedCb_"].toString().indexOf("_wx_loadedCb_") > 0) {
          window["_wx_loadedCb_"] = new Function();
        }
        callbacks.dataLoaded = function (newData) {
          window["_wx_loadedCb_"](newData);
          sendAppMessage(newData);
        };
        // 然后就绪
        callbacks.ready && callbacks.ready(argv);
      } else {
        // 就绪状态
        callbacks.ready && callbacks.ready(argv);
        sendAppMessage(data);
      }
    });
  }

  /**
   * 分享到腾讯微博
   * @param    {Object}  data    待分享的信息
   * @p-config  {String}  link    链接地址
   * @p-config  {String}  desc    描述
   *
   * @param    {Object}  callbacks 相关回调方法
   * @p-config  {Boolean}  async          ready方法是否需要异步执行,默认false
   * @p-config  {Function} ready(argv)       就绪状态
   * @p-config  {Function} dataLoaded(data)    数据加载完成后调用,async为true时有用,也可以为空
   * @p-config  {Function} cancel(resp)  取消
   * @p-config  {Function} fail(resp)   失败
   * @p-config  {Function} confirm(resp)  成功
   * @p-config  {Function} all(resp)    无论成功失败都会执行的回调
   */
  function weixinShareWeibo(data, callbacks) {
    callbacks = callbacks || {};
    var shareWeibo = function (theData) {
      WeixinJSBridge.invoke('shareWeibo', {
        "content":theData.desc,
        "url":theData.link
      }, function (resp) {
        switch (resp.err_msg) {
          // share_weibo:cancel 用户取消
          case 'share_weibo:cancel':
            callbacks.cancel && callbacks.cancel(resp);
            break;
          // share_weibo:confirm 发送成功
          case 'share_weibo:confirm':
          case 'share_weibo:ok':
            callbacks.confirm && callbacks.confirm(resp);
            break;
          // share_weibo:fail 发送失败
          case 'share_weibo:fail':
          default:
            callbacks.fail && callbacks.fail(resp);
            break;
        }
        // 无论成功失败都会执行的回调
        callbacks.all && callbacks.all(resp);
      });
    };
    WeixinJSBridge.on('menu:share:weibo', function (argv) {
      if (callbacks.async && callbacks.ready) {
        window["_wx_loadedCb_"] = callbacks.dataLoaded || new Function();
        if(window["_wx_loadedCb_"].toString().indexOf("_wx_loadedCb_") > 0) {
          window["_wx_loadedCb_"] = new Function();
        }
        callbacks.dataLoaded = function (newData) {
          window["_wx_loadedCb_"](newData);
          shareWeibo(newData);
        };
        // 然后就绪
        callbacks.ready && callbacks.ready(argv);
      } else {
        // 就绪状态
        callbacks.ready && callbacks.ready(argv);
        shareWeibo(data);
      }
    });
  }


  /**
   * 新的分享接口
   * @param    {Object}  data    待分享的信息
   * @p-config  {String}  appId   公众平台的appId(服务号可用)
   * @p-config  {String}  imgUrl   图片地址
   * @p-config  {String}  link    链接地址
   * @p-config  {String}  desc    描述
   * @p-config  {String}  title   分享的标题
   *
   * @param    {Object}  callbacks 相关回调方法
   * @p-config  {Boolean}  async          ready方法是否需要异步执行,默认false
   * @p-config  {Function} ready(argv,shareTo)       就绪状态
   * @p-config  {Function} dataLoaded(data)    数据加载完成后调用,async为true时有用,也可以为空
   * @p-config  {Function} cancel(resp,shareTo)  取消
   * @p-config  {Function} fail(resp,shareTo)   失败
   * @p-config  {Function} confirm(resp,shareTo)  成功
   * @p-config  {Function} all(resp,shareTo)    无论成功失败都会执行的回调
   */
  function weixinGeneralShare(data, callbacks) {
    callbacks = callbacks || {};
    var generalShare = function (general,theData) {

      // 如果是分享到朋友圈,则需要把title和desc交换一下
      if(general.shareTo == 'timeline') {
        var title = theData.title;
        theData.title = theData.desc || title;
        theData.desc = title;
      }

      // 分享出去
      general.generalShare({
        "appid":theData.appId &#63; theData.appId : '',
        "img_url":theData.imgUrl,
        "link":theData.link,
        "desc":theData.desc,
        "title":theData.title,
        "img_width":"640",
        "img_height":"640"
      }, function (resp) {
        switch (resp.err_msg) {
          // general_share:cancel 用户取消
          case 'general_share:cancel':
            callbacks.cancel && callbacks.cancel(resp ,general.shareTo);
            break;
          // general_share:confirm 发送成功
          case 'general_share:confirm':
          case 'general_share:ok':
            callbacks.confirm && callbacks.confirm(resp ,general.shareTo);
            break;
          // general_share:fail 发送失败
          case 'general_share:fail':
          default:
            callbacks.fail && callbacks.fail(resp ,general.shareTo);
            break;
        }
        // 无论成功失败都会执行的回调
        callbacks.all && callbacks.all(resp ,general.shareTo);
      });
    };
    WeixinJSBridge.on('menu:general:share', function (general) {
      if (callbacks.async && callbacks.ready) {
        window["_wx_loadedCb_"] = callbacks.dataLoaded || new Function();
        if(window["_wx_loadedCb_"].toString().indexOf("_wx_loadedCb_") > 0) {
          window["_wx_loadedCb_"] = new Function();
        }
        callbacks.dataLoaded = function (newData) {
          window["_wx_loadedCb_"](newData);
          generalShare(general,newData);
        };
        // 然后就绪
        callbacks.ready && callbacks.ready(general,general.shareTo);
      } else {
        // 就绪状态
        callbacks.ready && callbacks.ready(general,general.shareTo);
        generalShare(general,data);
      }
    });
  }

  /**
   * 加关注(此功能只是暂时先加上,不过因为权限限制问题,不能用,如果你的站点是部署在*.qq.com下,也许可行)
   * @param    {String}  appWeixinId   微信公众号ID
   * @param    {Object}  callbacks    回调方法
   * @p-config  {Function} fail(resp)   失败
   * @p-config  {Function} confirm(resp)  成功
   */
  function addContact(appWeixinId,callbacks){
    callbacks = callbacks || {};
    WeixinJSBridge.invoke("addContact", {
      webtype: "1",
      username: appWeixinId
    }, function (resp) {
      var success = !resp.err_msg || "add_contact:ok" == resp.err_msg || "add_contact:added" == resp.err_msg;
      if(success) {
        callbacks.success && callbacks.success(resp);
      }else{
        callbacks.fail && callbacks.fail(resp);
      }
    })
  }

  /**
   * 调起微信Native的图片播放组件。
   * 这里必须对参数进行强检测,如果参数不合法,直接会导致微信客户端crash
   *
   * @param {String} curSrc 当前播放的图片地址
   * @param {Array} srcList 图片地址列表
   */
  function imagePreview(curSrc,srcList) {
    if(!curSrc || !srcList || srcList.length == 0) {
      return;
    }
    WeixinJSBridge.invoke('imagePreview', {
      'current' : curSrc,
      'urls' : srcList
    });
  }

  /**
   * 显示网页右上角的按钮
   */
  function showOptionMenu() {
    WeixinJSBridge.call('showOptionMenu');
  }


  /**
   * 隐藏网页右上角的按钮
   */
  function hideOptionMenu() {
    WeixinJSBridge.call('hideOptionMenu');
  }

  /**
   * 显示底部工具栏
   */
  function showToolbar() {
    WeixinJSBridge.call('showToolbar');
  }

  /**
   * 隐藏底部工具栏
   */
  function hideToolbar() {
    WeixinJSBridge.call('hideToolbar');
  }

  /**
   * 返回如下几种类型:
   *
   * network_type:wifi   wifi网络
   * network_type:edge   非wifi,包含3G/2G
   * network_type:fail   网络断开连接
   * network_type:wwan   2g或者3g
   *
   * 使用方法:
   * WeixinApi.getNetworkType(function(networkType){
   *
   * });
   *
   * @param callback
   */
  function getNetworkType(callback) {
    if (callback && typeof callback == 'function') {
      WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
        // 在这里拿到e.err_msg,这里面就包含了所有的网络类型
        callback(e.err_msg);
      });
    }
  }

  /**
   * 关闭当前微信公众平台页面
   */
  function closeWindow() {
    WeixinJSBridge.call("closeWindow");
  }

  /**
   * 当页面加载完毕后执行,使用方法:
   * WeixinApi.ready(function(Api){
   *   // 从这里只用Api即是WeixinApi
   * });
   * @param readyCallback
   */
  function wxJsBridgeReady(readyCallback) {
    if (readyCallback && typeof readyCallback == 'function') {
      var Api = this;
      var wxReadyFunc = function () {
        readyCallback(Api);
      };
      if (typeof window.WeixinJSBridge == "undefined"){
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', wxReadyFunc, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', wxReadyFunc);
          document.attachEvent('onWeixinJSBridgeReady', wxReadyFunc);
        }
      }else{
        wxReadyFunc();
      }
    }
  }

  return {
    version     :"2.0",
    ready      :wxJsBridgeReady,
    shareToTimeline :weixinShareTimeline,
    shareToWeibo  :weixinShareWeibo,
    shareToFriend  :weixinSendAppMessage,
    generalShare  :weixinGeneralShare,
    addContact   :addContact,
    showOptionMenu :showOptionMenu,
    hideOptionMenu :hideOptionMenu,
    showToolbar   :showToolbar,
    hideToolbar   :hideToolbar,
    getNetworkType :getNetworkType,
    imagePreview  :imagePreview,
    closeWindow   :closeWindow
  };
})();

The above is the js code shared by WeChat. I hope it will be helpful to everyone's learning.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment