Git Product home page Git Product logo

Comments (3)

liyouu avatar liyouu commented on August 15, 2024

第三步:整合两家提供通用sdk

这是我之前做sdk的一点心得,因为要脱敏的原因,不能直接将sdk开源,但是这个sdk做起来是相当简单的哟~

① 实现思路

http://thyrsi.com/t6/360/1534836364x-1404755516.png

② 部分实现逻辑

// 定义全局变量
const shareTwice = {
  config(shareConfig) {
    // 默认先从meta标签中获取配置项,约定好类似这样的meta源标签<meta name="shareTitle" value="分享名称" />
    const defaultConfig = {};
    const titleDom = document.getElementsByTagName('meta').shareTitle || document.getElementsByTagName('title')[0];      
    const descDom = document.getElementsByTagName('meta').shareDesc;
    const linkDom = document.getElementsByTagName('meta').shareLink; 
    const imageDom = document.getElementsByTagName('meta').shareImage;
    defaultConfig.title = titleDom.getAttribute('content') || titleDom.innerText;
    defaultConfig.desc = descDom ? descDom.getAttribute('content') : '';  
    defaultConfig.link = linkDom ? linkDom.getAttribute('content') : document.location.href;  
    defaultConfig.image = imageDom ? imageDom.getAttribute('content') : 'https://gw.alipayobjects.com/zos/rmsportal/PbxcajsXkcfiWIYdRxaw.jpg'; 
    defaultConfig.successFun = function() {}
    defaultConfig.failFun = function(err) {}
    
    // 或者使用config({})传入的配置项
    this.shareConfig = Object.assign(defaultConfig, shareConfig || {});

    // 判断是否为钉钉环境  
    this.isDing();
    // 判断是否为微信环境,按需加载sdk
    this.isWechat();
  },
  isWechat() {
    const me = this;
    const isWechat = ~window.navigator.userAgent.indexOf('MicroMessenger');
    if (isWechat) {
      const me = this;
      if (typeof window.wx === 'undefined') {
        me._loadScript('//res.wx.qq.com/open/js/jweixin-1.2.0.js', function() {
          me._shareInWechat();            
        })
      } else {
        me._shareInWechat();
      }  
    } 
  },
  isDing() {
    const me = this;
    const isDing = ~window.navigator.userAgent.indexOf('DingTalk');
    if (isDing) {
      if (typeof window.dd === 'undefined') {
        me._loadScript('//g.alicdn.com/ilw/ding/0.9.9/scripts/dingtalk.js', function () {
          me._shareInDing();          
        })
      } else {
        me._shareInDing();        
      }
    }
  },
  // 配置在钉钉环境下分享时的配置项
  _shareInDing() {
    const me = this;
    dd.ready(function(){
      dd.biz.navigation.setRight({
        show: true,
        control: true,
        text: '',
        onSuccess : function(result) {
          dd.biz.util.share({
            type: 0,
            url: me.shareConfig.link,
            title: me.shareConfig.title,
            content: me.shareConfig.desc,
            image: me.shareConfig.image,
            onSuccess : me.shareConfig.successFun,
            onFail : me.shareConfig.failFun,
          });
        },
        onFail : function(err) {}
      });
    });
  },
  // 配置在微信环境下分享时的配置项
  _shareInWechat() {
    const me = this;
    me._getConfigs(function( data ){
      data.link = data.url;
      delete data.url;
      // 需要后端提供的接口返回appId、timestamp、nonceStr、signature
      me.shareConfig = Object.assign(me.shareConfig, data);
      wx.config({
        debug: me.shareConfig.debug, 
        appId: me.shareConfig.appId, 
        timestamp: me.shareConfig.timestamp,
        nonceStr: me.shareConfig.nonceStr, 
        signature: me.shareConfig.signature,
        jsApiList: [
          'openEnterpriseChat',
          'openEnterpriseContact',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'onMenuShareQQ',
          'onMenuShareWeibo',
          'onMenuShareQZone'
        ]
      });
      wx.ready(() => {
        wx.onMenuShareTimeline({
          title: me.shareConfig.title,
          desc: me.shareConfig.desc,
          link: me.shareConfig.link,
          imgUrl: me.shareConfig.image,
          success: me.shareConfig.successFun,
          cancel: me.shareConfig.failFun
        });
        wx.onMenuShareAppMessage({
          title: me.shareConfig.title,
          desc: me.shareConfig.desc,
          link: me.shareConfig.link,
          imgUrl: me.shareConfig.image,
          success: me.shareConfig.successFun,
          cancel: me.shareConfig.failFun
        });
      })
    });
  },
  // 需要服务端提供一个 微信获取jssdk签名的接口,具体要看接口怎么实现
  _getConfigs(callback) {
     $.ajax({
          method: "POST",
          url: "some.php",
          data: {
              url: document.location.href.split('#')[0]
          }
     })
     .done(function( msg ) {
          callback();
     });
  },
  _loadScript(src, callback) {
    let script = document.createElement('script');
    script.setAttribute('async', 'async');
    script.setAttribute('src', src);
    script.setAttribute('charset', 'utf-8');
    script.onload = () => {
      callback();
    };
    document.getElementsByTagName('head')[0].appendChild(script);
  }
};

③ 在页面中引用

通过<script charset="utf-8" src="./share-twice.js"></script>引入

④ 在页面中进行配置

方式一(简洁方式):通过标签注入

<meta name="shareTitle" content="需要分享的Title">
<meta name="shareDesc" content="需要分享的描述内容">
<meta name="shareLink" content="https://newconnection.cainiao.com/cn/test/liyoutest.html">
<meta name="shareImage" content="https://gw.alicdn.com/tfs/TB1UlBCNXXXXXXCXXXXXXXXXXXX-97-97.png">
<meta name="shareAuto" content="true">

方式二(支持分享后的回调):通过ShareTiwce.config()进行配置

<script>
    shareTwice.config({
      title: '需要分享的Title',
      desc: '需要分享的描述内容',
      link: 'https://newconnection.cainiao.com/cn/test/liyoutest.html',
      image: 'https://gw.alicdn.com/tfs/TB1864sQpXXXXaaXpXXXXXXXXXX-35-40.png',
      successFun: function() {
        // 分享成功后的回调函数
        alert("share-twice: success");
      },
      failFun: function() {
        // 分享取消或失败后的回调函数
        alert("share-twice: cancel");
      }
    });
</script>

⑤ 注意事项

  1. shareTwice.config中的配置高于<meta>标签中的配置项
  2. shareTitle默认为<title>标签中的值
  3. shareLink默认为document.location.href
  4. shareImage默认值为https://gw.alipayobjects.com/zos/rmsportal/PbxcajsXkcfiWIYdRxaw.jpg
  5. shareAuto默认值为false 若不设置为true需要调用shareTwice.config({})进行初始化

from fe9-library.

laoya avatar laoya commented on August 15, 2024

正犹豫要不要自己写一个 刚好需要 拿走 谢啦

from fe9-library.

dumuchenglin123 avatar dumuchenglin123 commented on August 15, 2024

厉害厉害,问下,你这是在公司电脑上写的还是自己电脑上写的?公司里可以发布留言吗?

from fe9-library.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.