WPS guide for browser application integration

Keywords: Javascript Excel JQuery Firefox

Because the WPS plug-in uses NPAPI mechanism to interact with browsers, it is required that browsers using plug-ins must support NPAPI mechanism and enable NPAPI mechanism.

The following are common supported browsers and their versions:

  • FireFox browser 52 and versions less than 52 (NPAPI is no longer supported for versions higher than 52)

  • Chrome 45 and below (NPAPI is no longer supported for versions above 45)

  • 360 browser (NPAPI supported version)

  • UOS browser (NPAPI supported version)

When WPS Jinshan document is used for online editing or Tencent document, for professional users who need to use Excel, the solution of online Office document opening does not meet their needs, so they turn to customized version of WPS integrated embedded in BS application, of course, the funds are enough to consider excellent professional enterprise cooperation such as graphite document and grape city.

The final performance of the application is excellent, which is equivalent to directly embedding WPS into the web page to meet various needs. The only drawback is that this solution is not free, because we got the WPS installation package (version 11.8.2.8744) for development together. The browser is recommended to use 360 speed version (speed mode), with 1 rendering attached below

                    


Provide the api document (nphelper) provided by the official development team as of January 2020

Links: https://pan.baidu.com/s/1NnPXnOdsdnAh5v3SgNAYaQ Extraction code: 25gt

[in case of infringement, please contact the author personally to delete]

Next, start the code sharing steps:

1. First create demo.html

<!DOCTYPE XHTML>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- Suspension button meta -->
    <meta name="Author" content="Rin">
    <!-- Suspension button css -->
    <link rel="stylesheet" href="../css/asidenav.css">
    <!-- jquery On-line cdn -->
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <!-- oa np Plug-in unit js -->
    <script src="../js/wps_general.js"></script>
    <script src="../js/common.js"></script>
    <!-- loading Plug-in unit js -->
    <script src="../js/spin.min.js"></script>
    <title>NP Plug-in unit Demo</title>
    <!-- loading Load animation effects Start-->
    <script type="text/javascript">
        $(function() {
            var opts = {
                lines: 9, // The number of lines to draw
                length: 0, // The length of each line
                width: 10, // The line thickness
                radius: 15, // The radius of the inner circle
                corners: 1, // Corner roundness (0..1)
                rotate: 0, // The rotation offset
                color: '#000', // #rgb or #rrggbb
                speed: 1, // Rounds per second
                trail: 60, // Afterglow percentage
                shadow: false, // Whether to render a shadow
                hwaccel: false, // Whether to use hardware acceleration
                className: 'spinner', // The CSS class to assign to the spinner
                zIndex: 2e9, // The z-index (defaults to 2000000000)
                top: 'auto', // Top position relative to parent in px
                left: 'auto' // Left position relative to parent in px
            };
            var target = document.getElementById('foo');
            var spinner = new Spinner(opts).spin(target);
        })
    </script>
    <!-- loading End-->
    <script>
        //Initialization
        var wpsFrame = new WPSFrame;
        /**
         * Basic parameters
         */
        var app = "test";
        var userid = "A004";
        var sheetname;
        var filename = "1.xlsx"; //"Test document.xlsx";
        var filetype = getfiletype(filename); //"xls";
        const basepath = baseurl + "/wps/template/";
        //User document path
        var userfileurl = baseurl + "/" + app + "/" + userid + "/" + encodeURI(filename);
        //Template document path
        var templateurl = basepath + encodeURI(filename);
        //wps Installation package address
        var downloadurl = "http://abc.com/upload/soft/setup_CN_2052_11.8.2.8744_Professional_VBA_huayu.exe";
        //No Chinese required
        const remoteGetUrl = basepath + encodeURI(filename);
        remoteSaveUrl = baseurl + "/WpsCloudService/upload?app=" + app + "&userid=" + userid;
        /**
         * Get file type
         */
        function getfiletype(filename) {
            if (filename.indexOf("xls") != -1) {
                filetype = "xls";
            } else if (filename.indexOf("ppt") != -1) {
                filetype = "ppt";
            } else if (filename.indexOf("doc") != -1) {
                filetype = "doc";
            }
            return filetype;
        }
        /**
         * program execution
         */
        $(document).ready(function() {
            //Check whether the browser is 360
            if (!is360browser()) {
                alert("Your current browser does not support this plug-in, please replace it with 360 browser, and recommend 360 speed browser(Extreme speed mode),Better effect,Note: please download the Professional Edition WPS");
                return;
            }
            //Initialize control
            init(filetype)
                //open documents
            open(filetype, sheetname);
        })
        function openfile(filename, type) {
            userfileurl = baseurl + "/" + app + "/" + userid + "/" + encodeURI(filename);
            templateurl = basepath + encodeURI(filename);
            filetype = type;
            initchange(type)
            if ($("#sheet").val() == "") {
                sheetname = "";
            } else {
                sheetname = $("#sheet").val();
            }
            open(type, sheetname);
        }
        function savefile() {
            save(filetype);
        }
    </script>
</head>

<body>
    <!-- Load animation effects -->
    <div id="foo" style="width:100px; height:200px; position:absolute;left: 50%;margin-top: 360px;" hidden="hidden">
    </div>

    <div id="wps" align="right" style="width:100%; height:75%; margin:0 auto;">
    </div>
    <div style="text-align: left;margin-top: 50px;margin-left: 100px;">
        <label>Appoint Sheet page: </label><input type="text" id="sheet" /><br/><br/>
        <a href="http://abc.com/upload/soft/setup_CN_2052_11.8.2.8744_XXXX_VBA_ABC.exe"><b>Download the latest version of professional wps</b></a>
        <br/> Note: professional customized version must be downloaded before using this function WPS,360 Browser must be in speed mode. Compatibility mode is not supported
    </div>

    <!-- Suspension button Start-->
    <div id="nav">
        <svg width="0" height="0">
            <defs>
                <filter id="goo">
                    <feGaussianBlur in="SourceGraphic" stdDeviation="10" result="blur"></feGaussianBlur>
                    <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 19 -9" result="goo"></feColorMatrix>
                    <feComposite in="SourceGraphic" in2="goo" operator="atop"></feComposite>
                </filter>
            </defs>
        </svg>
        <div class="aside-nav bounceInUp animated" id="aside-nav">
            <label for="" class="aside-menu" title="Hold down and drag.">menu</label>

            <a href="javascript:void(0)" onclick="openfile('1.xlsx','xls')" title="Excel" class="menu-item menu-first">Excel</a>
            <a href="javascript:void(0)" onclick="openfile('1.docx','doc')" title="Word" class="menu-item menu-second">Word</a>
            <a href="javascript:void(0)" onclick="openfile('1.pptx','ppt')" title="PPT" class="menu-item menu-third">PPT</a>
            <a href="javascript:void(0)" onclick="savefile()" title="Preservation" class="menu-item menu-fourth">Preservation</a>
        </div>
    </div>
</body>
</html>

2. Decompose initialization and opening methods and saving methods in $(document).ready

Because of the solution, the browser must support NPAPI, so currently only 360 browser can be used, or other browsers described above

① Initialize plug-in

/**
 * No height and width by default, 100% original
 * Initializing plug-ins, defining properties
 * @param {*File type doc,xls,ppt} doctype 
 */
function init(doctype) {
    plugin.setAttribute("type", "application/x-wps-np-plugin");
    plugin.setAttribute("height", "100%");
    plugin.setAttribute("width", "100%");
    plugin.setAttribute("id", "DocFrame1");
    //Document type definition
    if (doctype == "doc") {
        plugin.setAttribute("app", "wps");
    } else if (doctype == "xls") {
        plugin.setAttribute("app", "et");
    } else if (doctype == "ppt") {
        plugin.setAttribute("app", "wpp");
    }
    var obj = document.getElementById('wps');
    obj.appendChild(plugin);
    return plugin;
}

② Open remote resources

The process here is to download the remote resources first, then open the downloaded local temporary documents, and then upload them, so as to achieve the similar effect of modifying the cloud documents directly.

Because the current version of the official version is also in iteration, optimizing and testing some interfaces, at present, the interface of Word is relatively perfect, the opening and saving of demo have been realized, and the method provided by vba is called. Because our business is relatively simple, this time only describes opening and saving.

The rest of the functions are left to interested readers to study on their own, and the grammar is consistent with VBA.

function open(filetype, param) {
    //Loading animation loading
    $("#foo").show();
    //Download network resources and return to local path
    var res = false;
    //Download the user file to the local, and return the temporary file url
    url = plugin.application.downloadFile(userfileurl);
    if (url.indexOf('Error') != -1) {
        //Download file user file failed, download template file
        url = plugin.application.downloadFile(templateurl);
    }
    //Open local temporary file
    res = plugin.application.openDocument(url, false);
    if (res) {
        //Load animation off
        $("#foo").hide();
        console.log("Open method executed successfully" + new Date());
    }
    if (filetype == "xls") {
        //Define objects for later save methods
        workbook = plugin.application.ActiveWorkbook;
        if (param != "" && param != undefined) {
            //The calling method of the specified sheet page when the version number is opened
            plugin.application.get_Worksheets(param).select();
        }
    } else if (filetype == "ppt") {
        workbook = plugin.application.ActivePresentation;
    }
}

Preservation

function save(filetype) {
    var tempurl = url;
    var arr = tempurl.split(".");
    tempurl = arr[0] + "kls." + arr[1];
    //Save to local
    if (filetype == "doc") {
        //Save as save locally
        plugin.application.SaveAs(tempurl);
    } else if (filetype == "xls") {
        //This version number supports saving Excel in editing status
        plugin.application.ExitEdit();
        tempurl = url;
        //Save to local
        workbook.Save();
    } else if (filetype == "ppt") {
        //Objects defined when opening, save as file and save locally
        workbook.SaveAs(tempurl);
    }
    //Upload files to the server, remote saveurl server save interface, tempurl local temporary files
    var exc = plugin.UploadFile(remoteSaveUrl, tempurl)
    alert(exc);
}

Up to the above, the basic opening and saving functions have been realized. For more information, see https://open.wps.cn/docs/office Official document, browser application integration embedded WPS guide.

④ The server saves the file. The following example code is version C

Other versions can be captured and analyzed by referring to the official demo provided after cooperation

Or refer to the standard http protocol (JAVA version) https://blog.csdn.net/SJh3322/article/details/78435097

public string upload(string app,string userid)
        {
            string path = string.Empty;
            path = "~/" + app + "/" + userid + "/";
            //get files
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null)
            {
                //Does this exist app application
                if (System.IO.Directory.Exists(Server.MapPath(path)) == false)
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(path));
                }
                string fileName = file.FileName;
                string extension = Path.GetExtension(fileName);
                fileName = fileName.Substring(0, fileName.Length - extension.Length);
                path = path + fileName.Replace("kls",string.Empty)+ extension;
                if (System.IO.File.Exists(Path.GetFullPath(path)))
                {
                    System.IO.File.Delete(Path.GetFullPath(path));
                }
                file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
            }
            return "success";
        }


So far, browser application integration embedded WPS, open server documents and save functions, currently only supports Excel, Word, PPT.

I hope I can give a reference to the small partners in need, and also welcome you to give some suggestions.

Posted by jme on Thu, 16 Jan 2020 23:02:03 -0800