PageSourceSearch

https://smp.askdoctorslab.jp/static/js/embedded_form.js

js askdoctorslab.jp collected 2026-10-08 03:29:56 UTC 12,996 bytes, 363 lines download raw bytes

1// Namespace setup
2// eslint-disable-next-line no-use-before-define
3var smpform = smpform || {};
4
5// Allow console log
6(function () {
7    "use strict";
8
9    /**
10     * key: embedded form code
11     * value: form option
12     * */
13    let formOptions = {};
14
15    // Error code
16    const errorCode = {
17            "serverError"                 : "EF100 : ERROR_SERVER_ERROR",
18            "timeout"                     : "EF101 : ERROR_TIMEOUT",
19            "invalidResponse"             : "EF102 : ERROR_INVALID_RESPONSE",
20            "serviceUnavailable"          : "EF103 : ERROR_SERVICE_UNAVAILABLE",
21            "notFoundHtmlElement"         : "EF104 : ERROR_NOT_FOUND_HTML_ELEMENT",
22            "notFoundFormData"            : "EF105 : ERROR_NOT_FOUND_FORM_DATA",
23            "failedExecutionCallbackFunc" : "EF300 : ERROR_FAILED_EXECUTE_CALLBACK_FUNC",
24            "invalidExecutionTiming"      : "EF301 : ERROR_INVALID_EXECUTION_TIMING",
25            "invalidCallbackFunc"         : "EF302 : ERROR_INVALID_CALLBACK_FUNC"
26    };
27    // Error html message
28    const errorMsg = {
29        "serviceUnavailable" : "<p>只今、システムメンテナンスを実施しています。</p>",
30        "timeout"            : "<p>大変混みあっています。しばらく時間をおいて再度お試しください。</p>",
31        "notFoundFormData"   : "<p>エラーが発生しました。画面を再読み込みしてください。</p>",
32        "serverError"        : "<p>エラーが発生しました。しばらく時間をおいて再度お試しください。</p>",
33        "invalidResponse"    : "<p>エラーが発生しました。しばらく時間をおいて再度お試しください。</p>"
34    };
35
36    // Http status
37    const  httpStatus = {
38        "OK"                 : 200,
39        "notFound"           : 404,
40        "serviceUnavailable" : 503
41    };
42
43        // Submit after type
44    const  submitAfterType = {
45        "messageOutput" : "1",
46        "redirect"      : "2"
47    };
48
49    // Conversion timing type
50    const executionTimingType = { "onCompleted" : "onCompleted" };
51
52    smpform = {
53        /**
54         * formOpt
55         * - policyText: Privacy Policy Text. e.g. attribute3. default attribute1
56         * - submitWord: Submit Button Word
57         * - showPolicy: Show Privacy Policy. default hidden
58         *
59         * callbackOpt
60         * - executionTiming: Callback function execution timing
61         * - callbackFunc: Callback function
62         * */
63        // Load smp form data
64        "loadForm" : function (embeddedFormCode, url, formOpt, callbackOpt) {
65            const req = new XMLHttpRequest();
66
67            let src = "";
68            formOptions[embeddedFormCode] = formOpt || {};
69
70            if (embeddedFormCode && url && document.getElementById(embeddedFormCode)) {
71                src = url + "/public/embeddedapplication/add/" + encodeURIComponent(embeddedFormCode);
72            }
73            else {
74                // Embedded form tag not found
75                outputErrorLog(errorCode.notFoundHtmlElement);
76
77                return;
78            }
79
80            req.open("GET", src + getRequestParamsByObject( formOptions[embeddedFormCode] ));
81
82            if ( callbackOpt && !(verifyCallbackFuncOpt(callbackOpt)) ) {
83                return;
84            }
85            // 30s
86            req.timeout = 30000;
87
88            // Done
89            req.onload = function () {
90                if (req.status === httpStatus.OK || req.status === httpStatus.notFound) {
91                    try {
92                        const resultObject = JSON.parse(req.responseText);
93
94                        outputResponse(resultObject, embeddedFormCode, callbackOpt);
95                    }
96                    catch (e) {
97                        // Invalid response
98                        outputErrorLog(errorCode.invalidResponse);
99                    }
100                }
101                else if (req.status === httpStatus.serviceUnavailable) {
102                    outputErrorLog(errorCode.serviceUnavailable);
103                }
104                else {
105                    outputErrorLog(errorCode.serverError);
106                }
107            };
108
109
110            // Connection error
111            req.onerror = function () {
112                outputErrorLog(errorCode.serviceUnavailable);
113            };
114
115            // Timeout
116            req.ontimeout = function () {
117                outputErrorLog(errorCode.timeout);
118            };
119
120            req.send();
121        }
122    };
123
124    // Submit form
125    function submitForm(formData, callbackOpt) {
126        let embeddedFormCode = "",
127            requestUrl = "";
128
129        if (formData) {
130            embeddedFormCode = formData.parentNode.getAttribute("id");
131            requestUrl = formData.getAttribute("action");
132
133            // Disable submit button
134            formData.smpSubmit.disabled = true;
135        }
136        else {
137            outputErrorLog(errorCode.notFoundFormData);
138
139            return;
140        }
141
142        if (!embeddedFormCode) {
143            outputErrorLog(errorCode.notFoundFormData);
144
145            return;
146        }
147        else if (!requestUrl) {
148            rewriteHtml(errorMsg.notFoundFormData);
149
150            return;
151        }
152
153        const req = new XMLHttpRequest(),
154            camvid = loadCookie("__CAMVID"),
155            camsid = loadCookie("__CAMSID"),
156            formDataObject = new FormData(formData);
157
158        formDataObject.append("__CAMVID", camvid.__CAMVID);
159        formDataObject.append("__CAMSID", camsid.__CAMSID);
160
161        Object.keys(formOptions[embeddedFormCode]).map(function(key){
162            formDataObject.append(key, formOptions[embeddedFormCode][key]);
163        });
164
165        req.open("POST", requestUrl);
166
167        // 30s
168        req.timeout = 30000;
169
170        // Done
171        req.onload = function () {
172            if (req.readyState === XMLHttpRequest.DONE) {
173                if (req.status === httpStatus.OK || req.status === httpStatus.notFound) {
174                    try {
175                        const resultObject = JSON.parse(req.responseText);
176
177                        outputResponse(resultObject, embeddedFormCode, callbackOpt);
178                    }
179                    catch (e) {
180                        // Invalid response
181                        rewriteHtml(embeddedFormCode, errorMsg.invalidResponse);
182                    }
183                }
184                else if (req.status === httpStatus.serviceUnavailable) {
185                    rewriteHtml(embeddedFormCode, errorMsg.serviceUnavailable);
186                }
187            }
188            else {
189                rewriteHtml(embeddedFormCode, errorMsg.serverError);
190            }
191        };
192
193        // Connection error
194        req.onerror = function () {
195            rewriteHtml(embeddedFormCode, errorMsg.serviceUnavailable);
196        };
197
198        // Timeout
199        req.ontimeout = function () {
200            rewriteHtml(embeddedFormCode, errorMsg.timeout);
201        };
202
203        req.send(formDataObject);
204    }
205
206    // Response parse & output
207    function outputResponse(resultObject, embeddedFormCode, callbackOpt) {
208        if (resultObject.application_status === "input_data" && resultObject.element) {
209            // Form output or validation error
210            rewriteHtml(embeddedFormCode, resultObject.element);
211
212            // Set reCAPTCHA
213            if (resultObject.recaptcha_script) {
214                let script1 = document.createElement("script"),
215                    script2 = document.createElement("script");
216
217                script1.innerHTML = resultObject.recaptcha_script;
218                script2.src = resultObject.recaptcha_js;
219                script2.async = "async";
220                script2.defer = "defer";
221                document.getElementById(embeddedFormCode).appendChild(script1);
222                document.getElementById(embeddedFormCode).appendChild(script2);
223            }
224            const submitButton = document.querySelector("#" + embeddedFormCode + " .ss_btnArea input");
225
226            submitButton.addEventListener("click", function (e) {
227                const loaderElm = document.querySelector("#" + embeddedFormCode + " .ss_submit_loader");
228
229                loaderElm.style.display = "inline";
230                submitForm(e.target.form, callbackOpt);
231            });
232        }
233        else if (resultObject.application_status === "complete" && resultObject.complete_value) {
234            if (resultObject.submit_after_type === submitAfterType.messageOutput) {
235                changeEmbFormHeight( embeddedFormCode );
236                // Output application complete message
237                const completeElementStr = "<div class='ss_complete_message'><span>" + resultObject.complete_value + "</span></div>";
238
239                rewriteHtml(embeddedFormCode, completeElementStr);
240
241                if (callbackOpt) {
242                    executeCallbackFunc(embeddedFormCode, executionTimingType.onCompleted, callbackOpt);
243                }
244            }
245            else if (resultObject.submit_after_type === submitAfterType.redirect) {
246                // Redirect
247                location.href = resultObject.complete_value;
248            }
249            else {
250                rewriteHtml(embeddedFormCode, errorMsg.invalidResponse);
251            }
252        }
253        else if (resultObject.application_status === "complete" && !resultObject.complete_value) {
254            const completeElementStr = "<div class='ss_complete_message'><span></span></div>";
255            changeEmbFormHeight( embeddedFormCode );
256            rewriteHtml(embeddedFormCode, completeElementStr);
257        }
258        else if (resultObject.application_status === "error") {
259            if (resultObject.error_type === "view" && resultObject.element) {
260                // Output error message
261                rewriteHtml(embeddedFormCode, resultObject.element);
262                changeEmbFormHeight(embeddedFormCode);
263            }
264            else if (resultObject.error_type === "message" && resultObject.res_message) {
265                // Output error log
266                outputErrorLog(resultObject.res_message);
267            }
268            else {
269                outputErrorLog(errorCode.invalidResponse);
270            }
271        }
272        else {
273            outputErrorLog(errorCode.invalidResponse);
274        }
275    }
276
277    // Html rewrite
278    function rewriteHtml(embeddedFormCode, htmlString) {
279        try {
280            const targetElement = document.getElementById(embeddedFormCode);
281            targetElement.innerHTML = htmlString;
282        }
283        catch (e) {
284            outputErrorLog(errorCode.notFoundHtmlElement);
285        }
286    }
287
288    // Output error log
289    function outputErrorLog(errorCode) {
290        const logTemplate = "[SMP Form Error] ";
291
292        console.log(logTemplate + errorCode);
293    }
294
295    // Get cookie information
296    function loadCookie(cookieKey) {
297        const trackingInfo = [],
298            cookies = document.cookie.split("; ");
299
300        let i = 0,
301            value = "";
302
303        if (document.cookie !== "") {
304            for (i; i < cookies.length; i++) {
305                value = cookies[i].split("=");
306                if (value[0] === cookieKey) {
307                    trackingInfo[value[0]] = decodeURIComponent(value[1]);
308                }
309            }
310        }
311
312        return trackingInfo;
313    }
314
315    // External conversion service
316    function executeCallbackFunc(embeddedFormCode, executionTimingType, callbackOpt) {
317        try {
318            if (callbackOpt.executionTiming === executionTimingType) {
319                callbackOpt.callbackFunc();
320            }
321        }
322        catch (e) {
323            outputErrorLog(errorCode.failedExecutionCallbackFunc);
324        }
325    }
326    function changeEmbFormHeight( embeddedFormCode ) {
327        const elem = document.getElementById( embeddedFormCode );
328        if( elem ) {
329            elem.style.height = elem.clientHeight + "px";
330        }
331    }
332    function getRequestParamsByObject( paramObj ) {
333        const optionParam = Object.keys(paramObj).map(function(key){ return key+"="+ paramObj[key] }).join("&");
334        return !optionParam ? "" : "?"+optionParam;
335    }
336
337    function verifyExecutionTiming (executionTiming) {
338        if (!executionTiming || !(executionTiming in executionTimingType)) {
339            outputErrorLog(errorCode.invalidExecutionTiming);
340            return false;
341        }
342        return true;
343    }
344
345    function verifyCallbackFunc (callbackFunc) {
346        if (typeof callbackFunc !== "function") {
347            outputErrorLog(errorCode.invalidCallbackFunc);
348            return false;
349        }
350        return true;
351    }
352
353    function verifyCallbackFuncOpt(callbackOpt) {
354        const isValidExecutionTiming = verifyExecutionTiming(callbackOpt.executionTiming),
355            isValidCallbackFunc = verifyCallbackFunc(callbackOpt.callbackFunc);
356
357        return isValidExecutionTiming && isValidCallbackFunc;
358    }
359}());
360
361// eslint rule
362/* global smpform: true */
363/* eslint no-console: "off"*/

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.