後臺測試小工具--獲取微信的code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
    <style>
        .btn {
            font-size: 2rem;
        }
        input{
            width: 100%;
        }
    </style>
</head>
<body>

<input type="text" class="input">
<br>
<button class="btn">獲取code</button>

<!--複製能力-->
<script>
   const copy = (() => {
      const Document = window.document;

      // 如果document不存在,無法複製
      if (!Document)
         throw new Error('document is undefined!');

      const getCopyElem = (() => {
         let copyElem = null;
         return () => copyElem || (copyElem = createCopyTextarea())
      })();

      function createCopyTextarea() {
         let textarea = Document.createElement('textarea');
         let style = textarea.style;
         // 確保元素存在於dom樹上而又不被用戶看到,且儘量不影響其他元素;
         style.position = 'fixed';
         style.left = '100%';
         style.top = '100%';
         style.opacity = '0';
         style.width = '1px'; // 若元素大小爲0, 會無法選中導致複製失敗
         style.height = '1px';
         style.border = 'none';
         style.padding = '0';
         style.margin = '0';
         style.overflow = 'hidden';
         Document.body.appendChild(textarea);
         return textarea;
      }

      /**
       * @function copy    -- 複製內容到粘貼板
       *
       * @param {String} text    -  要複製的文本內容
       * @return {Boolean}       -  複製結果
       */
      return function copy(text, inputElement = null) {
         let copyElem = inputElement || getCopyElem();
         if (!copyElem)
            return false;

         copyElem.value = text;       // 改變輸入框的值
         copyElem.select();           // 選中值
         let res = Document.execCommand("Copy");   // 執行瀏覽器複製命令
         copyElem.blur();
         return res;
      }
   })();
</script>

<!--依賴的工具函數-->
<script>

   /**
    * 轉換地址欄參數
    */
   function parseQueryString(url) {
      var str = url.split("?")[1] || '',    //通過?得到一個數組,取?後面的參數
         items = str.split("&");    //分割成數組
      var arr, name, value;
      var obj = {};

      for (var i = 0; i < items.length; i++) {
         arr = items[i].split("=");    //["key0", "0"]
         name = arr[0];
         value = arr[1];
         obj[name] = value;
      }
      return obj;
   }


   /**
    * 轉換參數爲get類型
    */
   function parseDataToUrl(url, obj) {
      if (typeof url !== "string" || typeof obj !== "object")
         return url;
      let reurl = url + "?";
      let keys = Object.keys(obj);
      keys.forEach(key => reurl += key + "=" + obj[key]/*encodeURIComponent(obj[key])*/ + "&");
      reurl = reurl.substring(0, reurl.length - 1);
      return reurl;
   }


   /**
    * 將當前地址欄轉換爲回調地址uri
    */
   function getRedirectUri() {
      let {
         origin,
         pathname,
         search,
         hash,
      } = location;
      search = '?' + search.slice(1).split('&').filter(query => !query.includes('code=') && !query.includes('state=')).join('&');
      return encodeURIComponent(origin + pathname + search + hash);
   }

</script>

<!--微信授權操作-->
<script>

   // 微信授權地址
   const connect = 'https://open.weixin.qq.com/connect/oauth2/authorize';
   // const connect = 'http://static.pxb.micropig.cn/items/get_code.html';

   // 微信授權請求參數
   const wxData = {
      appid: 'wx753a3c4c7a501de8',
      redirect_uri: getRedirectUri(),//encodeURIComponent與encodeURI不一樣
      response_type: 'code',
      // scope: 'snsapi_base',
      scope: 'snsapi_userinfo',
      state: '1',
   };

   /**
    * 跳轉頁面進行微信登錄授權
    */
   function doWxLogin() {
      location.href = parseDataToUrl(connect, wxData)
   }

</script>

<!--頁面邏輯-->
<script>
   // DOM 元素
   const $btn = document.querySelector('.btn'),
      $input = document.querySelector('.input');

   // 按鈕綁定事件
   $btn.onclick = doWxLogin;

   // 獲取地址欄參數
   let data = parseQueryString(location.href);

   console.log(data);

   // 沒有code, 執行授權登錄
   if (!data.code)
      doWxLogin();
   // 有code
   else {
      copy(data.code, $input);
      alert($input.value === data.code ? '複製成功' : '複製失敗')
   }


</script>

</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章