wps加載項在vue2項目中的應用(publish模式)

wps加載項在vue2項目中的應用

應用代碼:
wps.js

/**
 * WPS OA助手-WPS啓動方法入口
 */
var pluginsMode = location.search.split("=")[1]; //截取url中的參數值
var pluginType = WpsInvoke.ClientType.wps; //加載項類型wps,et,wpp
var pluginName = "WpsOAAssist"; //加載項名稱
var wpsClient = new WpsClient(pluginType); //初始化一個多進程對象,多進程時才需要
var clientStr = pluginName + pluginType + "ClientId";
//單進程封裝開始
/**
 * 此方法是根據wps_sdk.js做的調用方法封裝
 * 可參照此定義
 * @param {*} funcs         這是在WPS加載項內部定義的方法,採用JSON格式(先方法名,再參數)
 * @param {*} front         控制着通過頁面執行WPS加載項方法,WPS的界面是否在執行時在前臺顯示
 * @param {*} jsPluginsXml  指定一個新的WPS加載項配置文件的地址,動態傳遞jsplugins.xml模式,例如:http://127.0.0.1:3888/jsplugins.xml
 * @param {*} isSilent      隱藏打開WPS,如果需要隱藏,那麼需要傳遞front參數爲false
 */

export function _Wps(funcs, front, jsPluginsXml, isSilent) {
    var info = {};
    info.funcs = funcs;
    if (isSilent) {
        //隱藏啓動時,front必須爲false
        front = false;
    }
    /**
     * 下面函數爲調起WPS,並且執行加載項WpsOAAssist中的函數dispatcher,該函數的參數爲業務系統傳遞過去的info
     */
    if (pluginsMode != 2) {
        //單進程
        singleInvoke(info, front, jsPluginsXml, isSilent);
    } else {
        //多進程
        multInvoke(info, front, jsPluginsXml, isSilent);
    }
}

//單進程
function singleInvoke(info, front, jsPluginsXml, isSilent) {
    WpsInvoke.InvokeAsHttp(
        pluginType, // 組件類型
        pluginName, // 插件名,與wps客戶端加載的加載的插件名對應
        "dispatcher", // 插件方法入口,與wps客戶端加載的加載的插件代碼對應,詳細見插件代碼
        info, // 傳遞給插件的數據
        function (result) {
            console.log(result, 44545)
            // 調用回調,status爲0爲成功,其他是錯誤
            if (result.status) {
                if (result.status == 100) {
                    WpsInvoke.AuthHttpesCert(
                        '請在稍後打開的網頁中,點擊"高級" => "繼續前往",完成授權。'
                    );
                    return;
                }
                alert(result.message);
            } else {
                console.log(result.response);
                showresult(result.response);
            }
        },
        front,
        jsPluginsXml,
        isSilent
    );

    /**
     * 接受WPS加載項發送的消息
     * 接收消息:WpsInvoke.RegWebNotify(type,name,callback)
     * WPS客戶端返回消息: wps.OAAssist.WebNotify(message)
     * @param {*} type 加載項對應的插件類型
     * @param {*} name 加載項對應的名字
     * @param {func} callback 接收到WPS客戶端的消息後的回調函數,參數爲接受到的數據
     */
    WpsInvoke.RegWebNotify(pluginType, pluginName, handleOaMessage);
}
//多進程
function multInvoke(info, front, jsPluginsXml, isSilent) {
    wpsClient.jsPluginsXml = jsPluginsXml
        ? jsPluginsXml
        : "http://192.168../cdn/wps-oa/jsplugins.xml"; //這裏改成自己起的服務地址
    if (localStorage.getItem(clientStr)) {
        wpsClient.clientId = localStorage.getItem(clientStr);
    }
    if (isSilent) {
        wpsClient.StartWpsInSilentMode(pluginName, function () {
            //隱藏啓動後的回調函數
            mult(info, front);
        });
    } else {
        mult(info, front);
    }
    wpsClient.onMessage = handleOaMessage;
}
//多進程二次封裝
function mult(info, front) {
    wpsClient.InvokeAsHttp(
        pluginName, // 插件名,與wps客戶端加載的加載的插件名對應
        "dispatcher", // 插件方法入口,與wps客戶端加載的加載的插件代碼對應,詳細見插件代碼
        info, // 傳遞給插件的數據
        function (result) {
            // 調用回調,status爲0爲成功,其他是錯誤
            if (wpsClient.clientId) {
                localStorage.setItem(clientStr, wpsClient.clientId);
            }
            if (result.status !== 0) {
                console.log(result);
                if (result.message == '{"data": "Failed to send message to WPS."}') {
                    wpsClient.IsClientRunning(function (status) {
                        console.log(status);
                        if (status.response == "Client is running.")
                            alert(
                                "任務發送失敗,WPS 正在執行其他任務,請前往WPS完成當前任務"
                            );
                        else {
                            wpsClient.clientId = "";
                            wpsClient.notifyRegsitered = false;
                            localStorage.setItem(clientStr, "");
                            mult(info);
                        }
                    });
                    return;
                } else if (result.status == 100) {
                    // WpsInvoke.AuthHttpesCert('請在稍後打開的網頁中,點擊"高級" => "繼續前往",完成授權。')
                    return;
                }
                alert(result.message);
            } else {
                console.log(result.response);
            }
        },
        front
    );
}
function handleOaMessage(data) {
    console.log(data);
}

function handleOaFunc1(message) {
    alert("我是函數handleOaFunc1,我接收到的參數是:" + message);
}
function handleOaFunc2(message) {
    alert("我是函數handleOaFunc2,我接收到的參數是:" + message);
    var span = window.parent.document.getElementById("webnotifyspan");
    span.innerHTML = message;
}
/**
 * 處理WPS加載項的方法返回值
 *
 * @param {*} resultData
 */
function showresult(resultData) {
    let json = eval("(" + resultData + ")");
    switch (json.message) {
        case "GetDocStatus": {
            let docstatus = json.docstatus;
            if (typeof docstatus != "undefined") {
                let str =
                    "文檔保存狀態:" +
                    docstatus.saved +
                    "\n文檔字數:" +
                    docstatus.words +
                    "\n文檔頁數:" +
                    docstatus.pages;
                alert(str);
            }
        }
    }
}

wpsFun.js

/**
 * WPS OA助手公用方法
 *
 */
import { wps_sdk } from "@/util/wpsjsrpcsdk.js";
import { _Wps } from "@/util/wps.js";
import { _Et } from "@/util/et.js";
// 打開文檔
export function openDoc(data) {
    //  保存文檔上傳路徑
    let baseUrl = "";
    let port = "/path";
    data.uploadPath = baseUrl + port + "? "filepath=" + data.filePath + "&originalName=" + data.originalName;
    if (data.onLoadType == "wps") {
        _Wps([
            {
                OpenDoc: {
                    docId: data.docId || "", // 文檔ID
                    uploadPath: data.uploadPath, // 保存文檔上傳路徑
                    fileName: data.fileName, // 文件路徑
                    uploadFieldName: data.uploadFieldName || "", // 文件上傳名稱
                    userName: store.state.user.userInfo.nick_name || ""
                }
            }
        ]); // OpenDoc方法對應於OA助手dispatcher支持的方法名
    } else if (data.onLoadType == "et") {
        _Et([
            {
                OpenDoc: {
                    docId: data.docId || "", // 文檔ID
                    uploadPath: data.uploadPath, // 保存文檔上傳路徑
                    fileName: data.fileName, // 文件路徑
                    uploadFieldName: data.uploadFieldName || "", // 文件上傳名稱
                    userName: store.state.user.userInfo.nick_name || ""
                },
            }
        ]); // OpenDoc方法對應於OA助手dispatcher支持的方法名
    }
}

/**
 * WPS OA助手啓動封裝方法
 */
(function(global, factory) {
  "use strict";

  if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = factory(global, true);
  } else {
    factory(global);
  }
})(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
  "use strict";

  var bFinished = true;

  /**
   * 兼容IE低版本的創建httpobj對象的方法
   * @returns httpobj,可用於進行數據傳輸的http的對象
   */
  function getHttpObj() {
    var httpobj = null;
    if (IEVersion() < 10) {
      try {
        httpobj = new XDomainRequest();
      } catch (e1) {
        httpobj = new createXHR();
      }
    } else {
      httpobj = new createXHR();
    }
    return httpobj;
  }
  //兼容IE低版本的創建xmlhttprequest對象的方法
  /**
   * 兼容IE低版本的創建xmlhttprequest對象的方法
   * @returns xmlhttprequest對象,兼容低版本IE
   */
  function createXHR() {
    if (typeof XMLHttpRequest != "undefined") {
      //兼容高版本瀏覽器
      return new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") {
      //IE6 採用 ActiveXObject, 兼容IE6
      var versions = [
        //由於MSXML庫有3個版本,因此都要考慮
        "MSXML2.XMLHttp.6.0",
        "MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp"
      ];

      for (var i = 0; i < versions.length; i++) {
        try {
          return new ActiveXObject(versions[i]);
        } catch (e) {
          //跳過
        }
      }
    } else {
      throw new Error("您的瀏覽器不支持XHR對象");
    }
  }

  /**
   * 通過該接口給服務器發請求
   * @param {*} options       參數對象,具體包含的參數如下:
   * @param {*} url           網頁路徑,傳輸地址
   * @param {*} type          傳輸類型,POST / GET / PUT
   * @param {*} sendData      傳輸的數據
   * @param {*} callback      回調函數
   * @param {*} tryCount      請求失敗後的嘗試次數
   * @param {*} bPop          是否彈出瀏覽器提示對話框
   * @param {*} timeout       請求等待響應的時間,超過時間請求實效
   * @param {*} concurrent    請求是否同步發送
   * @param {*} client        wpsclient對象
   * @returns NULL
   */
  function startWps(options) {
    console.log("startWps",options);
    if (!bFinished && !options.concurrent) {
      if (options.callback)
        options.callback({
          status: 1,
          message: "上一次請求沒有完成"
        });
      return;
    }
    bFinished = false;

    function startWpsInnder(tryCount) {
      console.log("startWpsInnder",tryCount);
      if (tryCount <= 0) {
        if (bFinished) return;
        bFinished = true;
        if (options.callback)
          options.callback({
            status: 2,
            message: "請允許瀏覽器打開WPS Office"
          });
        return;
      }
      var xmlReq = getHttpObj();
      //WPS客戶端提供的接收參數的本地服務,HTTP服務端口爲58890,HTTPS服務端口爲58891
      //這倆配置,取一即可,不可同時啓用
      xmlReq.open("POST", options.url);
      xmlReq.onload = function(res) {
        bFinished = true;
        if (initCloudsvr == true) {
          initCloudsvr = false;
        }
        if (options.callback) {
          if (
            res.target.response == '{"data": "Failed to send message to WPS."}'
          ) {
            options.callback({
              status: 1,
              message:
                IEVersion() < 10 ? xmlReq.responseText : res.target.response
            });
          } else {
            options.callback({
              status: 0,
              response:
                IEVersion() < 10 ? xmlReq.responseText : res.target.response
            });
          }
        }
      };
      xmlReq.ontimeout = xmlReq.onerror = function(res) {
        xmlReq.bTimeout = true;
        if (
          tryCount == options.tryCount &&
          options.bPop &&
          initCloudsvr == false
        ) {
          //打開wps並傳參
          InitWpsCloudSvr();
        }
        setTimeout(function() {
          startWpsInnder(tryCount - 1);
        }, 1000);
      };
      if (IEVersion() < 10) {
        xmlReq.onreadystatechange = function() {
          if (xmlReq.readyState != 4) return;
          if (xmlReq.bTimeout) {
            return;
          }
          if (xmlReq.status === 200) xmlReq.onload();
          else xmlReq.onerror();
        };
      }
      xmlReq.timeout = options.timeout;
      xmlReq.send(options.sendData);
    }
    startWpsInnder(options.tryCount);
    return;
  }

  var fromCharCode = String.fromCharCode;
  // encoder stuff
  var cb_utob = function(c) {
    if (c.length < 2) {
      var cc = c.charCodeAt(0);
      return cc < 0x80
        ? c
        : cc < 0x800
        ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))
        : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +
          fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
          fromCharCode(0x80 | (cc & 0x3f));
    } else {
      var cc =
        0x10000 +
        (c.charCodeAt(0) - 0xd800) * 0x400 +
        (c.charCodeAt(1) - 0xdc00);
      return (
        fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) +
        fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) +
        fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +
        fromCharCode(0x80 | (cc & 0x3f))
      );
    }
  };
  var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
  var utob = function(u) {
    return u.replace(re_utob, cb_utob);
  };
  var _encode = function(u) {
    var isUint8Array =
      Object.prototype.toString.call(u) === "[object Uint8Array]";
    if (isUint8Array) return u.toString("base64");
    else return btoa(utob(String(u)));
  };

  if (typeof window.btoa !== "function") window.btoa = func_btoa;

  function func_btoa(input) {
    var str = String(input);
    var chars =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    for (
      // initialize result and counter
      var block, charCode, idx = 0, map = chars, output = "";
      // if the next str index does not exist:
      //   change the mapping table to "="
      //   check if d has no fractional digits
      str.charAt(idx | 0) || ((map = "="), idx % 1);
      // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
      output += map.charAt(63 & (block >> (8 - (idx % 1) * 8)))
    ) {
      charCode = str.charCodeAt((idx += 3 / 4));
      if (charCode > 0xff) {
        throw new InvalidCharacterError(
          "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."
        );
      }
      block = (block << 8) | charCode;
    }
    return output;
  }

  /**
   * 將字符串進行Base64編碼
   * @param {*} u         需要編碼的數據
   * @param {*} urisafe   返回值,編碼後的數據
   * @returns             urisafe
   */
  var encode = function(u, urisafe) {
    return !urisafe
      ? _encode(u)
      : _encode(String(u))
          .replace(/[+\/]/g, function(m0) {
            return m0 == "+" ? "-" : "_";
          })
          .replace(/=/g, "");
  };

  /**
   * 獲取IE瀏覽器版本
   * @returns     IE瀏覽器版本
   */
  function IEVersion() {
    var userAgent = navigator.userAgent; //取得瀏覽器的userAgent字符串
    var isIE =
      userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判斷是否IE<11瀏覽器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判斷是否IE的Edge瀏覽器
    var isIE11 =
      userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIE) {
      var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
      reIE.test(userAgent);
      var fIEVersion = parseFloat(RegExp["$1"]);
      if (fIEVersion == 7) {
        return 7;
      } else if (fIEVersion == 8) {
        return 8;
      } else if (fIEVersion == 9) {
        return 9;
      } else if (fIEVersion == 10) {
        return 10;
      } else {
        return 6; //IE版本<=7
      }
    } else if (isEdge) {
      return 20; //edge
    } else if (isIE11) {
      return 11; //IE11
    } else {
      return 30; //不是ie瀏覽器
    }
  }

  /**
   * 啓動wps客戶端,加載項執行操作,無返回值
   * @param {*} options       參數對象,詳情見下:
   * @param {*} clientType    加載項類型, wps / wpp / et
   * @param {*} name          加載項名稱
   * @param {*} func          客戶端加載項要執行的方法
   * @param {*} param         客戶端家鄉執行方法的參數
   * @param {*} urlBase       網頁路徑前綴
   * @param {*} callback      回調函數
   * @param {*} tryCount      請求失敗後的嘗試次數
   * @param {*} bPop          是否彈出瀏覽器提示對話框
   * @param {*} wpsclient     wpsclient對象
   */
  function WpsStart(options) {
    console.log("WpsStart", options);
    var startInfo = {
      name: options.name,
      function: options.func,
      info: options.param.param,
      jsPluginsXml: options.param.jsPluginsXml
    };
    var strData = JSON.stringify(startInfo);
    if (IEVersion() < 10) {
      try {
        eval("strData = '" + JSON.stringify(startInfo) + "';");
      } catch (err) {}
    }

    var baseData = encode(strData);
    var url = options.urlBase + "/" + options.clientType + "/runParams";
    var data = "ksowebstartup" + options.clientType + "://" + baseData;
    startWps({
      url: url,
      sendData: data,
      callback: options.callback,
      tryCount: options.tryCount,
      bPop: options.bPop,
      timeout: 5000,
      concurrent: false,
      client: options.wpsclient
    });
  }

  /**
   * 服務端版本爲空時,通過該接口啓動wps
   * @param {*} options       參數對象,詳情見下:
   * @param {*} clientType    加載項類型, wps / wpp / et
   * @param {*} name          加載項名稱
   * @param {*} func          客戶端加載項要執行的方法
   * @param {*} param         客戶端家鄉執行方法的參數
   * @param {*} urlBase       網頁路徑前綴
   * @param {*} callback      回調函數
   * @param {*} wpsclient     wpsclient對象
   * @param {*} concurrent    請求是否同步發送
   */
  function WpsStartWrap(options) {
    console.log("WpsStartWrap");
    WpsStart({
      clientType: options.clientType,
      name: options.name,
      func: options.func,
      param: options.param,
      urlBase: options.urlBase,
      callback: options.callback,
      tryCount: 4,
      bPop: true,
      wpsclient: options.wpsclient
    });
  }

  /**
   * 支持瀏覽器觸發,WPS有返回值的啓動
   *
   * @param {*} clientType	組件類型
   * @param {*} name			WPS加載項名稱
   * @param {*} func			WPS加載項入口方法
   * @param {*} param			參數:包括WPS加載項內部定義的方法,參數等
   * @param {*} callback		回調函數
   * @param {*} tryCount		重試次數
   * @param {*} bPop			是否彈出瀏覽器提示對話框
   */
  var exId = 0;
  function WpsStartWrapExInner(options) {
    console.log("WpsStartWrapExInner", options);
    var infocontent = options.param.param;
    if (!options.wpsclient || options.wpsclient.single) {
      infocontent = JSON.stringify(options.param.param);
      var rspUrl = options.urlBase + "/transferEcho/runParams";
      var time = new Date();
      var cmdId = "js" + time.getTime() + "_" + exId;
      var funcEx = "var res = " + options.func;
      var cbCode =
        "var xhr = new XMLHttpRequest();xhr.open('POST', '" +
        rspUrl +
        "');xhr.send(JSON.stringify({id: '" +
        cmdId +
        "', response: res}));"; //res 爲func執行返回值
      var infoEx = infocontent + ");" + cbCode + "void(0";
      options.func = funcEx;
      infocontent = infoEx;
    }
    var startInfo = {
      name: options.name,
      function: options.func,
      info: infocontent,
      showToFront: options.param.showToFront,
      jsPluginsXml: options.param.jsPluginsXml
    };

    var strData = JSON.stringify(startInfo);
    if (IEVersion() < 10) {
      try {
        eval("strData = '" + JSON.stringify(startInfo) + "';");
      } catch (err) {}
    }

    var baseData = encode(strData);
    var wrapper;

    if (!options.wpsclient || options.wpsclient.single) {
      var url = options.urlBase + "/transfer/runParams";
      var data = "ksowebstartup" + options.clientType + "://" + baseData;
      wrapper = {
        id: cmdId,
        app: options.clientType,
        data: data,
        serverId: serverId,
        mode: options.silentMode ? "true" : "false"
      };
    } else {
      var url = options.urlBase + "/transferEx/runParams";
      wrapper = {
        id: options.wpsclient.clientId,
        app: options.clientType,
        data: baseData,
        mode: options.wpsclient.silentMode ? "true" : "false",
        serverId: serverId
      };
    }
    wrapper = JSON.stringify(wrapper);
    startWps({
      url: url,
      sendData: wrapper,
      callback: options.callback,
      tryCount: options.tryCount,
      bPop: options.bPop,
      timeout: 0,
      concurrent: options.concurrent,
      client: options.wpsclient
    });
  }

  var serverVersion = "wait";
  var cloudSvrStart = true;
  var initCloudsvr = false;
  /**
   * 獲取服務端版本號的接口
   * @param {*} options       參數對象,詳情見下:
   * @param {*} clientType    加載項類型, wps / wpp / et
   * @param {*} name          加載項名稱
   * @param {*} func          客戶端加載項要執行的方法
   * @param {*} param         客戶端家鄉執行方法的參數
   * @param {*} urlBase       網頁路徑前綴
   * @param {*} callback      回調函數
   * @param {*} wpsclient     wpsclient對象
   * @param {*} concurrent    請求是否同步發送
   */
  function WpsStartWrapVersionInner(options) {
    console.log("WpsStartWrapVersionInner",options);
    if (serverVersion == "wait") {
      if (cloudSvrStart == false) {
        InitWpsCloudSvr();
        initCloudsvr = true;
      }
      startWps({
        url: options.urlBase + "/version",
        sendData: JSON.stringify({ serverId: serverId }),
        callback: function(res) {
          if (res.status !== 0) {
            options.callback(res);
            return;
          }
          serverVersion = res.response;
          cloudSvrStart = true;
          options.tryCount = 1;
          options.bPop = false;
          if (serverVersion === "") {
            WpsStart(options);
          } else if (serverVersion < "1.0.1" && options.wpsclient) {
            options.wpsclient.single = true;
            WpsStartWrapExInner(options);
          } else {
            WpsStartWrapExInner(options);
          }
        },
        tryCount: 4,
        bPop: true,
        timeout: 5000,
        concurrent: options.concurrent
      });
    } else {
      options.tryCount = 4;
      options.bPop = true;
      if (serverVersion === "") {
        WpsStartWrap(options);
      } else if (serverVersion < "1.0.1" && options.wpsclient) {
        options.wpsclient.single = true;
        WpsStartWrapExInner(options);
      } else {
        WpsStartWrapExInner(options);
      }
    }
  }

  var HeartBeatCode =
    "function getHttpObj() {\n" +
    "            var httpobj = null;\n" +
    "            if (IEVersion() < 10) {\n" +
    "                try {\n" +
    "                    httpobj = new XDomainRequest();\n" +
    "                } catch (e1) {\n" +
    "                    httpobj = new createXHR();\n" +
    "                }\n" +
    "            } else {\n" +
    "                httpobj = new createXHR();\n" +
    "            }\n" +
    "            return httpobj;\n" +
    "        }\n" +
    "        \n" +
    "        function createXHR() {\n" +
    "            if (typeof XMLHttpRequest != 'undefined') {\n" +
    "                return new XMLHttpRequest();\n" +
    "            } else if (typeof ActiveXObject != 'undefined') {\n" +
    "                var versions = [\n" +
    "                    'MSXML2.XMLHttp.6.0',\n" +
    "                    'MSXML2.XMLHttp.3.0',\n" +
    "                    'MSXML2.XMLHttp'\n" +
    "                ];\n" +
    "        \n" +
    "                for (var i = 0; i < versions.length; i++) {\n" +
    "                    try {\n" +
    "                        return new ActiveXObject(versions[i]);\n" +
    "                    } catch (e) {\n" +
    "                        \n" +
    "                    }\n" +
    "                }\n" +
    "            } else {\n" +
    "                throw new Error('您的瀏覽器不支持XHR對象');\n" +
    "            }\n" +
    "        }\n" +
    "        \n" +
    "        function IEVersion() {\n" +
    "            var userAgent = navigator.userAgent; \n" +
    "            var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;\n" +
    "            var isEdge = userAgent.indexOf('Edge') > -1 && !isIE; \n" +
    "            var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;\n" +
    "            if (isIE) {\n" +
    "                var reIE = new RegExp('MSIE (\\d+\\.\\d+);');\n" +
    "                reIE.test(userAgent);\n" +
    "                var fIEVersion = parseFloat(RegExp['$1']);\n" +
    "                if (fIEVersion == 7) {\n" +
    "                    return 7;\n" +
    "                } else if (fIEVersion == 8) {\n" +
    "                    return 8;\n" +
    "                } else if (fIEVersion == 9) {\n" +
    "                    return 9;\n" +
    "                } else if (fIEVersion == 10) {\n" +
    "                    return 10;\n" +
    "                } else {\n" +
    "                    return 6; \n" +
    "                }\n" +
    "            } else if (isEdge) {\n" +
    "                return 20; \n" +
    "            } else if (isIE11) {\n" +
    "                return 11; \n" +
    "            } else {\n" +
    "                return 30; \n" +
    "            }\n" +
    "        }\n" +
    "        var heartBeatStart = false;\n" +
    "        function checkLastRegTime() {\n" +
    "            var now = new Date().valueOf();\n" +
    "            var TimeGap = now - LastRegTime;\n" +
    "            if (TimeGap > 5000 && !heartBeatStart) {\n" +
    "                HeartBeat();\n" +
    "                heartBeatStart = true;\n" +
    "            }\n" +
    "        }\n" +
    "        \n" +
    "        function HeartBeat() {\n" +
    "            var heartBeatItem = function () {\n" +
    "                var xhr = getHttpObj();\n" +
    "                xhr.onload = function (e) {\n" +
    "                    self.setTimeout(heartBeatItem, 5000);\n" +
    "                }\n" +
    "                xhr.onerror = function (e) {\n" +
    "                    self.setTimeout(heartBeatItem, 5000);\n" +
    "                }\n" +
    "                xhr.ontimeout = function (e) {\n" +
    "                    self.setTimeout(heartBeatItem, 5000);\n" +
    "                }\n" +
    "                xhr.open('POST', 'http://127.0.0.1:58890/askwebnotify', true);\n" +
    "                xhr.timeout = 2000;\n" +
    "                xhr.send(JSON.stringify(paramStr));\n" +
    "            }\n" +
    "            heartBeatItem();\n" +
    "        }\n" +
    "        \n" +
    "        var paramStr;\n" +
    "        var startCheck = false;\n" +
    "        self.addEventListener('message', function (event) {\n" +
    "            var data = event.data;\n" +
    "                paramStr = data.param\n" +
    "                paramStr.heartBeat = true\n" +
    "                LastRegTime = data.LastRegTime;\n" +
    "                if (!startCheck) {\n" +
    "                    startCheck = true;\n" +
    "                    self.setInterval(checkLastRegTime, 5000)\n" +
    "                }\n" +
    "        }, false);\n";
  /**
   * 生成guid的接口
   * @returns guid
   */
  function guid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
      var r = (Math.random() * 16) | 0,
        v = c == "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  /**
   * 開啓多用戶的接口
   */
  var serverId = undefined;
  function EnableMultiUser() {
    serverId = getServerId();
  }

  /**
   * 自定義協議啓動服務端
   * 默認不帶參數serverId,linux未升級之前不要使用多用戶
   */
  function InitWpsCloudSvr() {
    if (serverId == undefined)
      window.location.href = "ksoWPSCloudSvr://start=RelayHttpServer";
    //是否啓動wps彈框
    else
      window.location.href =
        "ksoWPSCloudSvr://start=RelayHttpServer" + "&serverId=" + serverId; //是否啓動wps彈框
  }

  /**
   * 獲取serverId的接口
   * @returns serverId
   */
  function getServerId() {
    if (window.localStorage) {
      if (localStorage.getItem("serverId")) {
        //
      } else {
        localStorage.setItem("serverId", guid());
      }
      return localStorage.getItem("serverId");
    } else {
      return guid();
    }
  }

  /**
   * 將字符串轉成二進制,這裏用來將字符串化後的js代碼轉成二進制文件
   * @param {*} code
   * @returns js文件對象的url
   */
  function codeToBlob(code) {
    var blob = new Blob([code], { type: "text/javascript" }); // 生成js文件對象
    var objectURL = window.URL.createObjectURL(blob); // 生成js文件的url
    return objectURL;
  }

  var RegWebNotifyMap = { wps: {}, wpp: {}, et: {} };
  var bWebNotifyUseTimeout = true;
  function WebNotifyUseTimeout(value) {
    bWebNotifyUseTimeout = value ? true : false;
  }
  var g_businessId = Number(
    Math.random()
      .toString()
      .substr(3, 5) + Date.parse(new Date())
  ).toString(36);
  var HeartBeatWorker;
  if (window.Worker) {
    try {
      HeartBeatWorker = new Worker(codeToBlob(HeartBeatCode));
    } catch (error) {
      //
    }
  }
  var g_LastRegTime;
  /**
   * 註冊一個前端頁面接收WPS傳來消息的方法
   * @param {*} clientType wps | et | wpp
   * @param {*} name WPS加載項的名稱
   * @param {*} callback 回調函數
   * @param {*} wpsclient wpsclient對象
   */
  function RegWebNotify(clientType, name, callback, wpsclient) {
    if (clientType != "wps" && clientType != "wpp" && clientType != "et")
      return;
    var paramStr = {};
    if (wpsclient) {
      if (wpsclient.notifyRegsitered == true) {
        return;
      }
      wpsclient.notifyRegsitered = true;
      paramStr = {
        clientId: wpsclient.clientId,
        name: name,
        type: clientType,
        serverId: serverId
      };
      if (HeartBeatWorker) paramStr.businessId = g_businessId;
    } else {
      if (typeof callback != "function") return;
      if (RegWebNotifyMap[clientType][name]) {
        RegWebNotifyMap[clientType][name] = callback;
        return;
      }
      var RegWebNotifyID = new Date().valueOf() + "";
      paramStr = {
        id: RegWebNotifyID,
        name: name,
        type: clientType,
        serverId: serverId
      };
      if (HeartBeatWorker) paramStr.businessId = g_businessId;
      RegWebNotifyMap[clientType][name] = callback;
    }

    var askItem = function() {
      var xhr = getHttpObj();
      xhr.onload = function(e) {
        if (xhr.responseText == "WPSInnerMessage_quit") {
          return;
        }
        try {
          var resText = JSON.parse(xhr.responseText);
          if (typeof resText == "object") {
            paramStr.messageId = resText.msgId;
          }
          if (wpsclient) {
            if (typeof resText.data == "object")
              // 如果發的數據是字符串化後的json對象,這裏的resText.data就是一個json對象,可以輸出自己想要的json數據
              wpsclient.OnRegWebNotify(resText.data.data);
            else wpsclient.OnRegWebNotify(resText.data);
          } else {
            var func = RegWebNotifyMap[clientType][name];
            if (typeof resText.data == "object")
              // 如果發的數據是字符串化後的json對象,這裏的resText.data就是一個json對象,可以輸出自己想要的json數據
              func(resText.data.data);
            else func(resText.data);
          }
        } catch (e) {
          // 這裏做一個容錯,即使json解析失敗,也要把msgId提取出來,發回給服務端,避免消息清不掉一直重複發送
          // 同時把data也取出來,但是格式無法保證
          var str = xhr.responseText;
          var idx1 = str.indexOf(":");
          var idx2 = str.indexOf(",");
          paramStr.messageId = parseInt(str.substring(idx1 + 1, idx2));
          var idx3 = str.indexOf('"data"');
          var idx4 = str.indexOf("}");
          var data = str.substring(idx3, idx4);
          if (wpsclient) {
            if (data) wpsclient.OnRegWebNotify(data);
            else wpsclient.OnRegWebNotify(xhr.responseText);
          } else {
            var func = RegWebNotifyMap[clientType][name];
            if (data) func(data);
            else func(xhr.responseText);
          }
        }
        window.setTimeout(askItem, 300);
      };
      xhr.onerror = function(e) {
        if (bWebNotifyUseTimeout) window.setTimeout(askItem, 1000);
        else window.setTimeout(askItem, 10000);
      };
      xhr.ontimeout = function(e) {
        if (bWebNotifyUseTimeout) window.setTimeout(askItem, 300);
        else window.setTimeout(askItem, 10000);
      };
      if (IEVersion() < 10) {
        xhr.onreadystatechange = function() {
          if (xhr.readyState != 4) return;
          if (xhr.bTimeout) {
            return;
          }
          if (xhr.status === 200) xhr.onload();
          else xhr.onerror();
        };
      }
      xhr.open("POST", GetUrlBase() + "/askwebnotify", true);
      if (bWebNotifyUseTimeout) xhr.timeout = 2000;
      if (HeartBeatWorker) {
        g_LastRegTime = new Date().valueOf();
        var param = {
          param: {
            name: name,
            type: clientType,
            businessId: g_businessId,
            serverId: serverId
          },
          LastRegTime: g_LastRegTime
        };
        HeartBeatWorker.postMessage(param);
      }
      xhr.send(JSON.stringify(paramStr));
    };
    window.setTimeout(askItem, 2000);
  }

  /**
   * 獲取網頁路徑前綴
   * @returns url前綴
   */
  function GetUrlBase() {
    if (location.protocol == "https:") return "https://127.0.0.1:58891";
    return "http://127.0.0.1:58890";
  }

  /**
   * 獲取服務端版本號的接口,這裏主要是初始化一些參數
   * @param {*} clientType    加載項類型, wps / wpp / et
   * @param {*} name          加載項名稱
   * @param {*} func          客戶端加載項要執行的方法
   * @param {*} param         客戶端家鄉執行方法的參數
   * @param {*} callback      回調函數
   * @param {*} showToFront   設置客戶端是否顯示到前面
   * @param {*} jsPluginsXml  設置加載項路徑
   * @param {*} silentMode    靜默啓動WPS
   */
  function WpsStartWrapVersion(
    clientType,
    name,
    func,
    param,
    callback,
    showToFront,
    jsPluginsXml,
    silentMode
  ) {
    var paramEx = {
      jsPluginsXml: jsPluginsXml ? jsPluginsXml : "",
      showToFront: typeof showToFront == "boolean" ? showToFront : true,
      param: typeof param == "object" ? param : JSON.parse(param)
    };
    var options = {
      clientType: clientType,
      name: name,
      func: func,
      param: paramEx,
      urlBase: GetUrlBase(),
      callback: callback,
      wpsclient: undefined,
      concurrent: true,
      silentMode: silentMode
    };
    WpsStartWrapVersionInner(options);
  }

  //從外部瀏覽器遠程調用 WPS 加載項中的方法
  var WpsInvoke = {
    InvokeAsHttp: WpsStartWrapVersion,
    InvokeAsHttps: WpsStartWrapVersion,
    RegWebNotify: RegWebNotify,
    ClientType: {
      wps: "wps",
      et: "et",
      wpp: "wpp"
    },
    CreateXHR: getHttpObj,
    IsClientRunning: IsClientRunning
  };

  window.wpsclients = [];
  /**
   * @constructor WpsClient           wps客戶端
   * @param {string} clientType       必傳參數,加載項類型,有效值爲"wps","wpp","et";分別表示文字,演示,電子表格
   */
  function WpsClient(clientType) {
    /**
     * 設置RegWebNotify的回調函數,加載項給業務端發消息通過該函數
     * @memberof WpsClient
     * @member onMessage
     */
    this.onMessage;

    /**
     * 設置加載項路徑
     * @memberof WpsClient
     * @member jsPluginsXml
     */
    this.jsPluginsXml;

    /**
     * 內部成員,外部無需調用
     */
    this.notifyRegsitered = false;
    this.clientId = "";
    this.concurrent = false;
    this.clientType = clientType;
    this.firstRequest = true;

    /**
     * 內部函數,外部無需調用
     * @param {*} options
     */
    this.initWpsClient = function(options) {
      options.clientType = this.clientType;
      options.wpsclient = this;
      options.concurrent = this.firstRequest ? true : this.concurrent;
      this.firstRequest = false;
      WpsStartWrapVersionInner(options);
    };

    /**
     * 以http啓動
     * @param {string} name              加載項名稱
     * @param {string} func              要調用的加載項中的函數行
     * @param {string} param             在加載項中執行函數func要傳遞的數據
     * @param {function({int, string})} callback        回調函數,status = 0 表示成功,失敗請查看message信息
     * @param {bool} showToFront         設置wps是否顯示到前面來
     * @return {string}                  "Failed to send message to WPS." 發送消息失敗,客戶端已關閉;
     *                                   "WPS Addon is not response." 加載項阻塞,函數執行失敗
     */
    this.InvokeAsHttp = function(name, func, param, callback, showToFront) {
      function clientCallback(res) {
        //this不是WpsClient
        if (res.status !== 0 || serverVersion < "1.0.1") {
          if (callback) callback(res);
          RegWebNotify(clientType, name, this.client.onMessage);
          return;
        }
        var resObject = JSON.parse(res.response);
        if (this.client.clientId == "") {
          this.client.clientId = resObject.clientId;
        }
        this.client.concurrent = true;
        if (typeof resObject.data == "object")
          res.response = JSON.stringify(resObject.data);
        else res.response = resObject.data;
        if (IEVersion() < 10) eval(" res.response = '" + res.response + "';");
        if (callback) callback(res);
        this.client.RegWebNotify(name);
      }
      var paramEx = {
        jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : "",
        showToFront: typeof showToFront == "boolean" ? showToFront : true,
        param: typeof param == "object" ? param : JSON.parse(param)
      };
      this.initWpsClient({
        name: name,
        func: func,
        param: paramEx,
        urlBase: GetUrlBase(),
        callback: clientCallback
      });
    };

    /**
     * 以https啓動
     * @param {string} name              加載項名稱
     * @param {string} func              要調用的加載項中的函數行
     * @param {string} param             在加載項中執行函數func要傳遞的數據
     * @param {function({int, string})} callback        回調函數,status = 0 表示成功,失敗請查看message信息
     * @param {bool} showToFront         設置wps是否顯示到前面來
     */
    this.InvokeAsHttps = function(name, func, param, callback, showToFront) {
      var paramEx = {
        jsPluginsXml: this.jsPluginsXml ? this.jsPluginsXml : "",
        showToFront: typeof showToFront == "boolean" ? showToFront : true,
        param: typeof param == "object" ? param : JSON.parse(param)
      };
      this.initWpsClient({
        name: name,
        func: func,
        param: paramEx,
        urlBase: GetUrlBase(),
        callback: callback
      });
    };

    /**
     * 內部函數,外部無需調用
     * @param {*} name
     */
    this.RegWebNotify = function(name) {
      RegWebNotify(this.clientType, name, null, this);
    };

    /**
     * 消息註冊函數的回調函數
     * @param {*} message   客戶端發來的消息
     */
    this.OnRegWebNotify = function(message) {
      if (this.onMessage) this.onMessage(message);
    };

    /**
     * 以靜默模式啓動客戶端
     * @param {string} name                 必傳參數,加載項名稱
     * @param {function({int, string})} [callback]         回調函數,status = 0 表示成功,失敗請查看message信息
     */
    this.StartWpsInSilentMode = function(name, callback) {
      function initCallback(res) {
        //this不是WpsClient
        if (res.status !== 0 || serverVersion < "1.0.1") {
          if (callback) callback(res);
          RegWebNotify(clientType, name, this.client.onMessage);
          return;
        }
        if (this.client.clientId == "") {
          this.client.clientId = JSON.parse(res.response).clientId;
          window.wpsclients[window.wpsclients.length] = {
            name: name,
            client: this.client
          };
        }
        res.response = JSON.stringify(JSON.parse(res.response).data);
        this.client.concurrent = true;
        if (callback) {
          callback(res);
        }
        this.client.RegWebNotify(name);
      }
      var paramEx = {
        jsPluginsXml: this.jsPluginsXml,
        showToFront: false,
        param: { status: "InitInSilentMode" }
      };
      this.silentMode = true;
      this.initWpsClient({
        name: name,
        func: "",
        param: paramEx,
        urlBase: GetUrlBase(),
        callback: initCallback
      });
    };

    /**
     * 顯示客戶端到最前面
     * @param {string} name             必傳參數,加載項名稱
     * @param {function({int, string})} [callback]     回調函數
     */
    this.ShowToFront = function(name, callback) {
      if (serverVersion < "1.0.1") {
        if (callback) {
          callback({
            status: 4,
            message: "當前客戶端不支持,請升級客戶端"
          });
          return;
        }
        return;
      }
      if (this.clientId == "") {
        if (callback)
          callback({
            status: 3,
            message: "沒有靜默啓動客戶端"
          });
        return;
      }
      var paramEx = {
        jsPluginsXml: "",
        showToFront: true,
        param: { status: "ShowToFront" }
      };
      this.initWpsClient({
        name: name,
        func: "",
        param: paramEx,
        urlBase: GetUrlBase(),
        callback: callback
      });
    };

    /**
     * 關閉未顯示出來的靜默啓動客戶端
     * @param {string} name             必傳參數,加載項名稱
     * @param {function({int, string})} [callback]     回調函數
     */
    this.CloseSilentClient = function(name, callback) {
      if (serverVersion < "1.0.1") {
        if (callback) {
          callback({
            status: 4,
            message: "當前客戶端不支持,請升級客戶端"
          });
          return;
        }
        return;
      }
      if (this.clientId == "") {
        if (callback)
          callback({
            status: 3,
            message: "沒有靜默啓動客戶端"
          });
        return;
      }
      var paramEx = {
        jsPluginsXml: "",
        showToFront: false,
        param: undefined
      };
      var func;
      if (this.clientType == "wps") func = "wps.WpsApplication().Quit";
      else if (this.clientType == "et") func = "wps.EtApplication().Quit";
      else if (this.clientType == "wpp") func = "wps.WppApplication().Quit";

      function closeSilentClient(res) {
        if (res.status == 0) this.client.clientId = "";
        if (callback) callback(res);
        return;
      }
      this.initWpsClient({
        name: name,
        func: func,
        param: paramEx,
        urlBase: GetUrlBase(),
        callback: closeSilentClient
      });
    };

    /**
     * 當前客戶端是否在運行,使用WpsClient.IsClientRunning()進行調用
     * @param {function({int, string})} [callback]      回調函數,"Client is running." 客戶端正在運行
     *                                                  "Client is not running." 客戶端沒有運行
     */
    this.IsClientRunning = function(callback) {
      if (serverVersion < "1.0.1") {
        if (callback) {
          callback({
            status: 4,
            message: "當前客戶端不支持,請升級客戶端"
          });
          return;
        }
        return;
      }
      IsClientRunning(this.clientType, callback, this);
    };
  }

  /**
   * 初始化sdk,用來減少在服務進程啓動時自定義協議彈框出現的次數
   */
  function InitSdk() {
    var url = GetUrlBase() + "/version";
    startWps({
      url: url,
      callback: function(res) {
        if (res.status !== 0) {
          cloudSvrStart = false;
          return;
        }
        if (serverVersion == "wait") {
          InitMultiUser();
        }
      },
      tryCount: 1,
      bPop: false,
      timeout: 1000
    });
  }
  InitSdk();

  /**
   * 初始化多用戶模式
   */
  function InitMultiUser() {
    var url = GetUrlBase() + "/version";
    startWps({
      url: url,
      sendData: JSON.stringify({ serverId: serverId }),
      callback: function(res) {
        if (res.status !== 0) {
          cloudSvrStart = false;
          return;
        }
        if (serverVersion == "wait") {
          serverVersion = res.response;
          cloudSvrStart = true;
        }
      },
      tryCount: 1,
      bPop: false,
      timeout: 1000
    });
  }

  if (typeof noGlobal === "undefined") {
    window.WpsInvoke = WpsInvoke;
    window.WpsClient = WpsClient;
    window.WebNotifyUseTimeout = WebNotifyUseTimeout;
    window.EnableMultiUser = EnableMultiUser;
  }

  /**
   * 當前客戶端是否在運行,使用WpsInvoke.IsClientRunning()進行調用
   * @param {string} clientType       加載項類型
   * @param {function} [callback]      回調函數,"Client is running." 客戶端正在運行
   *                                   "Client is not running." 客戶端沒有運行
   */
  function IsClientRunning(clientType, callback, wpsclient) {
    var url = GetUrlBase() + "/isRunning";
    var wrapper = {
      id: wpsclient == undefined ? undefined : wpsclient.clientId,
      app: clientType,
      serverId: serverId
    };
    wrapper = JSON.stringify(wrapper);
    startWps({
      url: url,
      sendData: wrapper,
      callback: callback,
      tryCount: 1,
      bPop: false,
      timeout: 2000,
      concurrent: true,
      client: wpsclient
    });
  }

  /**
   * 獲取publish.xml的內容
   * @param {*} callBack 回調函數
   */
  function WpsAddonGetAllConfig(callBack) {
    var baseData = JSON.stringify({ serverId: serverId });
    startWps({
      url: GetUrlBase() + "/publishlist",
      type: "POST",
      sendData: baseData,
      callback: callBack,
      tryCount: 3,
      bPop: true,
      timeout: 5000,
      concurrent: true
    });
  }

  /**
   * 檢查ribbon.xml文件是否有效
   * @param {*} element   參數對象
   * @param {*} callBack  回調函數
   */
  function WpsAddonVerifyStatus(element, callBack) {
    var xmlReq = getHttpObj();
    var offline = element.online === "false";
    var url = offline ? element.url : element.url + "ribbon.xml";
    xmlReq.open("POST", GetUrlBase() + "/redirect/runParams");
    xmlReq.onload = function(res) {
      if (offline && !res.target.response.startsWith("7z")) {
        callBack({ status: 1, msg: "不是有效的7z格式" + url });
      } else if (!offline && !res.target.response.startsWith("<customUI")) {
        callBack({ status: 1, msg: "不是有效的ribbon.xml, " + url });
      } else {
        callBack({ status: 0, msg: "OK" });
      }
    };
    xmlReq.onerror = function(res) {
      xmlReq.bTimeout = true;
      callBack({
        status: 2,
        msg: "網頁路徑不可訪問,如果是跨域問題,不影響使用" + url
      });
    };
    xmlReq.ontimeout = function(res) {
      xmlReq.bTimeout = true;
      callBack({ status: 3, msg: "訪問超時" + url });
    };
    if (IEVersion() < 10) {
      xmlReq.onreadystatechange = function() {
        if (xmlReq.readyState != 4) return;
        if (xmlReq.bTimeout) {
          return;
        }
        if (xmlReq.status === 200) xmlReq.onload();
        else xmlReq.onerror();
      };
    }
    xmlReq.timeout = 5000;
    var data = {
      method: "get",
      url: url,
      data: ""
    };
    var sendData = FormatSendData(data);
    xmlReq.send(sendData);
  }

  /**
   * 部署加載項,包括啓動enable / disable禁用 / disableall禁用所有
   * @param {*} element   參數對象
   * @param {*} cmd       具體操作,enable / disable / disableall
   * @param {*} callBack  回調函數
   */
  function WpsAddonHandleEx(element, cmd, callBack) {
    console.log("WpsAddonHandleEx", element, cmd, callBack)
    var data = FormatData(element, cmd);
    startWps({
      url: GetUrlBase() + "/deployaddons/runParams",
      type: "POST",
      sendData: data,
      callback: callBack,
      tryCount: 3,
      bPop: true,
      timeout: 5000,
      concurrent: true
    });
  }

  /**
   * 啓用加載項
   * @param {*} element   參數對象
   * @param {*} callBack  回調函數
   */
  function WpsAddonEnable(element, callBack) {
    WpsAddonHandleEx(element, "enable", callBack);
  }

  /**
   * 禁用加載項
   * @param {*} element   參數對象
   * @param {*} callBack  回調函數
   */
  function WpsAddonDisable(element, callBack) {
    WpsAddonHandleEx(element, "disable", callBack);
  }

wpsjsrpcsdk.js
  /**
   * 生成json格式的數據
   * @param {*} element   參數對象
   * @param {*} cmd       具體操作,enable / disable / disableall
   * @returns base64編碼後的數據
   */
  function FormatData(element, cmd) {
    var data = {
      cmd: cmd, //"enable", 啓用, "disable", 禁用, "disableall", 禁用所有
      name: element.name,
      url: element.url,
      addonType: element.addonType,
      online: element.online,
      version: element.version
    };
    return FormatSendData(data);
  }

  /**
   * 將json格式的數據字符串化,並進行base64編碼
   * @param {*} data  數據
   * @returns base64編碼後的數據
   */
  function FormatSendData(data) {
    var strData = JSON.stringify(data);
    if (IEVersion() < 10) eval("strData = '" + JSON.stringify(strData) + "';");

    if (serverVersion == "1.0.2") {
      var base64Data = encode(strData);
      return JSON.stringify({
        serverId: serverId,
        data: base64Data
      });
    } else {
      return encode(strData);
    }
  }
  //管理 WPS 加載項
  var WpsAddonMgr = {
    getAllConfig: WpsAddonGetAllConfig,
    verifyStatus: WpsAddonVerifyStatus,
    enable: WpsAddonEnable,
    disable: WpsAddonDisable
  };

  if (typeof noGlobal === "undefined") {
    window.WpsAddonMgr = WpsAddonMgr;
  }

  return { WpsInvoke: WpsInvoke, WpsAddonMgr: WpsAddonMgr, version: "1.0.21" };
});

et.js

var pluginsMode = location.search.split("=")[1];//截取url中的參數值
var pluginType = WpsInvoke.ClientType.et//加載項類型wps,et,wpp
var pluginName = "EtOAAssist";//加載項名稱
var wpsClient = new WpsClient(pluginType);//初始化一個多進程對象,多進程時才需要
var clientStr = pluginName + pluginType + "ClientId"
//單進程封裝開始
/**
 * 此方法是根據wps_sdk.js做的調用方法封裝
 * 可參照此定義
 * @param {*} funcs         這是在WPS加載項內部定義的方法,採用JSON格式(先方法名,再參數)
 * @param {*} front         控制着通過頁面執行WPS加載項方法,WPS的界面是否在執行時在前臺顯示
 * @param {*} jsPluginsXml  指定一個新的WPS加載項配置文件的地址,動態傳遞jsplugins.xml模式,例如:http://127.0.0.1:3888/jsplugins.xml
 * @param {*} isSilent      隱藏打開WPS,如果需要隱藏,那麼需要傳遞front參數爲false
 */


export function _Et(funcs, front, jsPluginsXml, isSilent) {
    var info = {};
    info.funcs = funcs;
    if (isSilent) {//隱藏啓動時,front必須爲false
        front = false;
    }
    /**
     * 下面函數爲調起WPS,並且執行加載項WpsOAAssist中的函數dispatcher,該函數的參數爲業務系統傳遞過去的info
     */
    if (pluginsMode != 2) {//單進程
        singleInvoke(info, front, jsPluginsXml, isSilent)
    } else {//多進程
        multInvoke(info, front, jsPluginsXml, isSilent)
    }

}

//單進程
function singleInvoke(info, front, jsPluginsXml, isSilent) {
    WpsInvoke.InvokeAsHttp(pluginType, // 組件類型
        pluginName, // 插件名,與wps客戶端加載的加載的插件名對應
        "dispatcher", // 插件方法入口,與wps客戶端加載的加載的插件代碼對應,詳細見插件代碼
        info, // 傳遞給插件的數據        
        function (result) { // 調用回調,status爲0爲成功,其他是錯誤
            if (result.status) {
                if (result.status == 100) {
                    WpsInvoke.AuthHttpesCert('請在稍後打開的網頁中,點擊"高級" => "繼續前往",完成授權。')
                    return;
                }
                alert(result.message)

            } else {
                console.log(result.response)
            }
        },
        front,
        jsPluginsXml,
        isSilent)

    /**
     * 接受WPS加載項發送的消息
     * 接收消息:WpsInvoke.RegWebNotify(type,name,callback)
     * WPS客戶端返回消息: wps.OAAssist.WebNotify(message)
     * @param {*} type 加載項對應的插件類型
     * @param {*} name 加載項對應的名字
     * @param {func} callback 接收到WPS客戶端的消息後的回調函數,參數爲接受到的數據
     */
    WpsInvoke.RegWebNotify(pluginType, pluginName, handleOaMessage)
}
//多進程
function multInvoke(info, front, jsPluginsXml, isSilent) {
    wpsClient.jsPluginsXml = jsPluginsXml ? jsPluginsXml : "http://192.168.21.5:9998/wps/jsplugins.xml"; //這裏改成自己起的服務地址
    if (localStorage.getItem(clientStr)) {
        wpsClient.clientId = localStorage.getItem(clientStr)
    }
    if (isSilent) {
        wpsClient.StartWpsInSilentMode(pluginName, function () {//隱藏啓動後的回調函數
            mult(info, front)
        })
    } else {
        mult(info, front)
    }
    wpsClient.onMessage = handleOaMessage
}
//多進程二次封裝
function mult(info, front) {
    wpsClient.InvokeAsHttp(
        pluginName, // 插件名,與wps客戶端加載的加載的插件名對應
        "dispatcher", // 插件方法入口,與wps客戶端加載的加載的插件代碼對應,詳細見插件代碼
        info, // 傳遞給插件的數據        
        function (result) { // 調用回調,status爲0爲成功,其他是錯誤
            if (wpsClient.clientId) {
                localStorage.setItem(clientStr, wpsClient.clientId)
            }
            if (result.status !== 0) {
                console.log(result)
                if (result.message == '{\"data\": \"Failed to send message to WPS.\"}') {
                    wpsClient.IsClientRunning(function (status) {
                        console.log(status)
                        if (status.response == "Client is running.")
                            alert("任務發送失敗,WPS 正在執行其他任務,請前往WPS完成當前任務")
                        else {
                            wpsClient.clientId = "";
                            wpsClient.notifyRegsitered = false;
                            localStorage.setItem(clientStr, "")
                            mult(info)
                        }
                    })
                    return;
                }
                else if (result.status == 100) {
                    // WpsInvoke.AuthHttpesCert('請在稍後打開的網頁中,點擊"高級" => "繼續前往",完成授權。')
                    return;
                }
                alert(result.message)
            } else {
                console.log(result.response)
            }
        },
        front)
}

function handleOaMessage(data) {
    console.log(data)
}
function GetUploadPath() {
    var url = document.location.host;
    return document.location.protocol + "//" + url + "/Upload";
}

function GetDemoPath(fileName) {

    var url = document.location.host;
    return document.location.protocol + "//" + url + "/file/" + fileName;
}

function newDoc() {
    _WpsInvoke([{
        "OpenDoc": {
            showButton: "btnSaveFile;btnSaveAsLocal"
        }
    }])
}

wps文件:我是放在public\cdn\wps-oa的,所以LoadPublishAddons方法裏面的/cdn/wps-oa要隨你放置的位置進行變動。

function LoadPublishAddons() {
         var addonList = document.getElementById("addonList");
  		var origin = window.location.origin
  var curList = [{"name":"WpsOAAssist","addonType":"wps","online":"true","multiUser":"false","url":origin + "/cdn/wps-oa/WpsOAAssist/"},{"name":"EtOAAssist","addonType":"et","online":"true","multiUser":"false","url":origin + "/cdn/wps-oa/EtOAAssist/"},{"name":"WppOAAssist","addonType":"wpp","online":"true","multiUser":"false","url":origin + "/cdn/wps-oa/WppOAAssist/"}];
  curList.forEach(function (element) {
      var param = JSON.stringify(element).replace("\"", "\'");
      UpdateElement(element, 'enable')
  });
}

wps文件下載

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