店小秘通用函数

通用函数

Ovu skriptu ne treba izravno instalirati. To je biblioteka za druge skripte koje se uključuju u meta direktivu // @require https://update.greasyfork.org/scripts/499487/1435607/%E5%BA%97%E5%B0%8F%E7%A7%98%E9%80%9A%E7%94%A8%E5%87%BD%E6%95%B0.js

// ==UserScript==
// @name        店小秘通用函数
// @namespace   Violentmonkey Scripts
// @license MIT
// @icon        https://www.dianxiaomi.com/favicon.ico
// @grant GM_xmlhttpRequest
// @version     0.0.4.2
// @author      KuromiNote
// ==UserScript==
const tool = {
    getTotalPage:async function(baseUrl,data=undefined,limtPage=-1,op='GET'){
      let book = [];
      if(!Object.keys(data).includes("pageNo")){
        return;
      }
      if(op.toUpperCase() === 'GET' && data){
        url = this.setUrlParam(baseUrl,data)
      }else{
        url = baseUrl;
      }
      var pageNo = +data['pageNo'];
      var firstPage = await new Promise((resolve) => {
        GM_xmlhttpRequest({
          method: op,
          url: url,
          data:this.decodeData(data),
          headers: {
              "Content-Type": "application/x-www-form-urlencoded"
          },
          onload: function (response) {
            html = $(response.responseText);
            resolve(html);
          }
        });
      });
      book.push(firstPage);
      var tasks = [];
      var totalPage = firstPage.find("#totalPage");
      if(totalPage.length === 0){
        totalPage = firstPage.closest("#totalPage");
      }
      if(totalPage.length === 0){
        totalPage = firstPage.find("#totalPages");
      }
      if(totalPage.length === 0){
        totalPage = firstPage.closest("#totalPages");
      }
      totalPage = +totalPage.val();
      if (limtPage >= 0 && limtPage <= totalPage){
          totalPage = limtPage;
      }
      for(var i=pageNo+1;i<=totalPage;++i){
        data['pageNo'] = i;
        if(op.toUpperCase() === 'GET' && data){
            url = this.setUrlParam(baseUrl,data);
        }
        tasks.push(new Promise((resolve) => {
          GM_xmlhttpRequest({
            method: op,
            url: url,
            data:this.decodeData(data),
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload: function (response) {
              html = $(response.responseText);
              resolve(html);
            }
          });
        }));
      }
      book = book.concat(await Promise.all(tasks));
      return book;
    },
    setUrlParam: function(url, param){
      return url+"?"+this.decodeData(param);
    },
    decodeData: function(data){
        return $.map(Object.keys(data),function(val){return `${val}=${data[val]? data[val]:''}`}).join("&");
    }
}