(function() { var take = function() { //DDP console.log("DDP init") const chatform=localStorage.getItem("chatform") if(window.location.pathname == "/shopping/lp.php"){ const paymentItem = localStorage.getItem("paymentItem") if(paymentItem){ var clickPaymentExe=()=>{ var clickPaymentInterval = setInterval(function () { const clickPayment = document.querySelector('[name="payment_kind"]') if(clickPayment){ //console.log("has paymentItem", paymentItem) clearInterval(clickPaymentInterval); setTimeout(() => { document.querySelector('[name="payment_kind"][value="'+ paymentItem +'"]').click() localStorage.removeItem("paymentItem") }, 1500); } }, 100); } clickPaymentExe() } } if(chatform){ // console.log("DDP") switch (window.location.pathname) { case '/': break; case '/shopping/complete': //at complete page var url = "https://pr.aqur.com/track"; function track(trackingData){ fetch(url, { method:"POST", headers:{ "Content-Type" : "application/json"}, body:trackingData }) .then(response => response.json()) .then(data => { console.log("Conversion Tracked!!") if(document.querySelector("#data_customer_id")){ let FormatURL; let URL; const orderId = document.querySelector("#botchan_order_id").innerText const customer_id = document.querySelector("#data_customer_id").getAttribute("value") //URL = window.location.href.endsWith("/") ? window.location.href.slice(0, -1) : window.location.href; function base64UrlEncode(str) { const base64 = btoa(encodeURIComponent(str)); return encodeURIComponent(base64); } FormatURL = "https://hadanature.jp/shopping/botchan/complete?order_id=" + base64UrlEncode(orderId) + "&customer_id=" + base64UrlEncode(customer_id); if(localStorage.getItem("urlParam")){ FormatURL = FormatURL + localStorage.getItem("urlParam") } var param1={ event: "redirect_thankPage", url: FormatURL } // console.log("redirect param=>", param1) localStorage.removeItem("urlParam") localStorage.removeItem("chatform"); window.parent.postMessage(param1, '*'); } }) } track(chatform) break; default: console.log('do nothing'); } }else{ console.log("No Chatform") } document.addEventListener("DOMContentLoaded", () => { //console.log("DOMContentLoaded") var param={ event: "chatform_DOMContentLoaded" } window.parent.postMessage(param, '*'); }) window.addEventListener("message", (event) => { //console.log("window message") if(event.data.event == "chatform_vframe_debug"){ //console.log("chatform_vframe_debug") } if(event.data.event == "chatform_bindForm"){ //console.log("DDP chatform_bindForm",event.data.data) var project = event.data.data; var arr = project.data; var chatform = { pid:project.pid, sid:project.sid, uuId:project.uuId, id:arr[arr.length-1].id } localStorage.setItem('chatform', JSON.stringify(chatform)); if(event.data.urlParam){ localStorage.setItem("urlParam", event.data.urlParam) } bindForm(arr) } if(event.data.event == "chatform_bindFormSubmit"){ //console.log("chatform_bindFormSubmit DDP") bindFormSubmit() } }) } setTimeout(take, 0); }()) async function bindForm(d){ //console.log("bind data => ",d) const fillInput = (selector, value) => { return new Promise((resolve, reject) => { let inputEvent = new InputEvent('change', { bubbles: true, cancelable: false }); const inputElement = document.querySelector(selector); if (inputElement) { inputElement.value = value; inputElement.dispatchEvent(inputEvent); resolve(`Input with name "${selector}" filled and event dispatched`); } else { reject(`Element with name "${selector}" not found.`); } }); }; const fillZipInput = (selector, value) => { return new Promise((resolve, reject) => { const inputField = document.querySelector(selector); if (!inputField) { reject(`Input field with selector "${selector}" not found.`); return; } inputField.value = value; const inputEvent = new Event('input', { bubbles: true, cancelable: true }); const changeEvent = new Event('change', { bubbles: true, cancelable: true }); inputField.dispatchEvent(inputEvent); inputField.dispatchEvent(changeEvent); setTimeout(() => { const dropdown = document.querySelector('ul.candidate.postcode_candidate.active'); if (!dropdown) { reject("Dropdown did not activate. Check your logic or timing."); return; } //最初のドロップダウン項目を見つけてクリックをシミュレートする const dropdownItem = dropdown.querySelector('li a.one-candidate'); if (dropdownItem) { const mousedownEvent = new MouseEvent('mousedown', { bubbles: true, cancelable: true }); const mouseupEvent = new MouseEvent('mouseup', { bubbles: true, cancelable: true }); const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true }); //event click dropdownItem.dispatchEvent(mousedownEvent); dropdownItem.dispatchEvent(mouseupEvent); dropdownItem.dispatchEvent(clickEvent); resolve(`Successfully interacted with dropdown item: ${dropdownItem.textContent}`); } else { reject("Dropdown item not found."); } }, 500); }); } const chooseSelectBox = (selectBoxSelector, value, useOptionVal = true) => { return new Promise((resolve, reject) => { let option = "" if(useOptionVal) { option = document.querySelector(`${selectBoxSelector} option[value='${value}']`); } else { option = document.querySelector(`${selectBoxSelector} option[label='${value}']`); } const selectElement = document.querySelector(`${selectBoxSelector}`); if (option && selectElement) { option.selected = true; const event = new Event('change', { bubbles: true, composed: true }) selectElement.dispatchEvent(event); resolve(`Select box with name '${selectBoxSelector}' set to option value '${value}' and event dispatched.`); } else { reject(new Error(`Select box with name '${selectBoxSelector}' and option value '${value}' not found.`)); } }); }; const fillInputKeyBoard = async (selector, value) => { const inputElement = document.querySelector(selector); if (inputElement) { // Focus on the input field const focusEvent = new FocusEvent('focus', { bubbles: true }); inputElement.dispatchEvent(focusEvent); // Clear the input field inputElement.value = ''; const inputClearEvent = new Event('input', { bubbles: true }); inputElement.dispatchEvent(inputClearEvent); // Simulate typing each character for (const char of value) { // Simulate keydown const keyDownEvent = new KeyboardEvent('keydown', { key: char, code: `Key${char.toUpperCase()}`, bubbles: true }); inputElement.dispatchEvent(keyDownEvent); // Update the value of the input field inputElement.value += char; // Simulate input event const inputEvent = new Event('input', { bubbles: true }); inputElement.dispatchEvent(inputEvent); // Simulate keypress const keyPressEvent = new KeyboardEvent('keypress', { key: char, code: `Key${char.toUpperCase()}`, bubbles: true }); inputElement.dispatchEvent(keyPressEvent); // Simulate keyup const keyUpEvent = new KeyboardEvent('keyup', { key: char, code: `Key${char.toUpperCase()}`, bubbles: true }); inputElement.dispatchEvent(keyUpEvent); // Add a slight delay between characters for realism await new Promise(resolve => setTimeout(resolve, 40)); } // Simulate Enter key press but prevent default behavior const enterKeyDownEvent = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true // Make it cancelable to prevent default form submission }); const prevented = !inputElement.dispatchEvent(enterKeyDownEvent); if (prevented) { console.log('Default action prevented.'); } const enterKeyUpEvent = new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', bubbles: true }); inputElement.dispatchEvent(enterKeyUpEvent); } }; const StrBinding_Submit_ChkError = async (streetVal) => { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Error check function const checkErrors = () => { const resultArr = []; const errorElements = document.querySelectorAll(".errormsg"); errorElements.forEach((val) => { if (val.innerText.trim() !== "") { resultArr.push(val.innerText.trim() + "。"); } val.innerHTML = ""; // Clear error messages }); if (resultArr.length > 0) { const errorTxt = resultArr.join("
"); const param = { event: "chatform_bindFormErrorFound", text: errorTxt, }; window.parent.postMessage(param, "*"); } }; // Submit action function const FormsubmitAction = () => { const submitEl = document.querySelector('img#img_buy_with_mm'); if (submitEl) { submitEl.click(); } else { console.error("Form Submit button not found"); } }; // Submit action function const ConfirmsubmitAction = () => { const submitEl = document.querySelector('#commit-button'); if (submitEl) { submitEl.click(); } else { console.error("Confirm Submit button not found"); } }; try { // Step 1 fill street data await fillInputKeyBoard('input[name="order_addr02"]', streetVal); await delay(2000); // Wait for 2 seconds document.querySelector("body").click(); FormsubmitAction(); // Wait before re-filling input await delay(1000); // Step 2 for second third check if(document.querySelector('input[name="order_addr02"]').value.trim() == ""){ console.log("inside second check") await fillInputKeyBoard('input[name="order_addr02"]', streetVal); await delay(2500); // Wait for 2.5 seconds document.querySelector("body").click(); FormsubmitAction(); } // Wait for 1 seconds await delay(1000); // Step 3 for sepcial third check if(document.querySelector('input[name="order_addr02"]').value.trim() == ""){ console.log("inside third check") await fillInputKeyBoard('input[name="order_addr02"]', streetVal); await delay(2500); // Wait for 2.5 seconds document.querySelector("body").click(); FormsubmitAction(); } // Step 4 checking error checkErrors(); // Step 5 confirm button click if(document.querySelector('#commit-button')){ await delay(500); // Wait for 0.5 seconds ConfirmsubmitAction() } } catch (error) { console.error("An error occurred during the process:", error); } }; var payment = findOption(d, "order[payment_attributes][payment_method_id]") localStorage.removeItem("paymentItem") localStorage.setItem("paymentItem", payment) if(document.querySelector('#login_area .customer_info')){ console.log("login done") const getChatform = localStorage.getItem("chatform") var url = "https://pr.aqur.com/track"; function track(trackingData){ fetch(url, { method:"POST", headers:{ "Content-Type" : "application/json"}, body:trackingData }) .then(response => response.json()) .then(data => { console.log("Conversion Tracked!!") var param2={ event: "redirect_thankPage", url: window.location.href } localStorage.removeItem("chatform"); window.parent.postMessage(param2, '*'); }) } track(getChatform) }else{ console.log("no login") try { await fillInput('input[name="order_name01"]', findValue(d, 'lastname')) await fillInput('input[name="order_name02"]', findValue(d, 'firstname')) await fillInput('input[name="order_kana01"]', findValue(d, 'furigana_firstname')) await fillInput('input[name="order_kana02"]', findValue(d, 'furigana_mei')) const zipElm = document.querySelector('input[name="order_zipcode"]') if(zipElm.value.trim() != findValue(d, 'zip')){ //console.log("work zipElm") await fillZipInput('input[name="order_zipcode"]', findValue(d, 'zip')) } await new Promise(resolve => setTimeout(resolve, 1000)); await fillInput('input[name="order_tel"]', findValue(d, "phone")) // const emlMail = document.querySelector('input[name="order_email"]') let tmpMail; // console.log("email=>", findValue(d, "email")) if(findValue(d, "email") == "Undefind" || !findValue(d, "email")){ var chars_email = "abcdefghijklmnopqrstuvwxyz0123456789"; var rand_str_email = ""; for (var i = 0; i < 10; i++) { rand_str_email += chars_email.charAt( Math.floor(Math.random() * chars_email.length) ); } tmpMail = rand_str_email + "@hadanature.jp"; await fillInput('input[name="order_email"]', tmpMail) }else{ await fillInput('input[name="order_email"]', findValue(d, "email")) } //temp password is tel await fillInput('input[name="customer_password"]', "a" + findValue(d, "phone")) document.querySelector('[name="payment_kind"][value="'+ payment +'"]').click() await new Promise(resolve => setTimeout(resolve, 500)); if (payment == "1") { await fillInput('[name="cardNumber"]', findValue(d, "dwfrm_billing_paymentMethods_creditCard_number")) let ccMonth = findValue(d, "dwfrm_billing_paymentMethods_creditCard_month") < 10 ? "0" + findValue(d, "dwfrm_billing_paymentMethods_creditCard_month") : findValue(d, "dwfrm_billing_paymentMethods_creditCard_month") await chooseSelectBox('select[name="cardExpirationMonth"]', ccMonth) let ccYear = findValue(d, "dwfrm_billing_paymentMethods_creditCard_year") await chooseSelectBox('select[name="cardExpirationYear"]', ccYear) await fillInput('[name="card_name1"]', findValue(d, "CardHolderName").split(" ")[0]) await fillInput('[name="card_name2"]', findValue(d, "CardHolderName").split(" ")[1]) } const streetElm = document.querySelector('input[name="order_addr02"]') let streetVal = findValue(d, 'street') + findValue(d,"building") //call function await StrBinding_Submit_ChkError(streetVal); } catch (error) { console.log(error) } } } function bindFormSubmit(){ console.log("DDP bindFormSubmit") } function base64UrlEncode(input) { // Convert the input string to a Base64-encoded string let base64 = btoa(input); // Convert Base64 to Base64 URL-safe format // Replace '+' with '-', '/' with '_', and remove '=' padding return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } function base64UrlDecode(input) { // Replace '-' with '+' and '_' with '/' and pad with '=' to restore Base64 format let base64 = input.replace(/-/g, '+').replace(/_/g, '/'); while (base64.length % 4 !== 0) { base64 += '='; } return atob(base64); } //default function function findOptionByCustomId(d,cid){ //console.log(n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId==cid){ if(item.options){ item.options.forEach(function(v) { if(v.checked){ //console.log(v) rtn = v } }) } } } return rtn } function findValue(d,n){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.values){ item.values.forEach(function(v) { //console.log(v.name, n) if(v.name==n){ //console.log(n, v.name) rtn = v.value } }) } } //console.log(n,rtn) return rtn } function selectByOptionText(selectElement, searchText) { for (let i = 0; i < selectElement.options.length; i++) { if (selectElement.options[i].text === searchText) { selectElement.selectedIndex = i; break; } } } //d= all Data, t=customerID, n=name function findValueByCustomID(d,t,n){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId == t){ //console.log("item", item) item.values.forEach(function(v) { //console.log(v.name, n) if(v.name==n){ rtn = v.value } }) } } //console.log(n,rtn) return rtn } function findOptionLabelByCustomID(d,t,n){ //console.log(d,n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.customId == t){ //console.log("item", item) item.options.forEach(function(v) { //console.log(v.name, n) if(v.checked){ rtn = v.label } }) } } //console.log(n,rtn) return rtn } //radio return single value function findOption(d,n){ //console.log(n) let value="Undefind"; rtn = value; for(var i=0; i < d.length; i++){ var item = d[i]; //console.log(item) if(item.options){ item.options.forEach(function(v) { if(v.name==n && v.checked){ //console.log(v) rtn = v.value } }) } } return rtn } //checkbox return array function findOptions(d,n){ rtn = []; for(var i=0; i < d.length; i++){ var item = d[i]; if(item.options){ item.options.forEach(function(v) { var reg = new RegExp(n) if(reg.test(v.name) && v.checked){ rtn.push(v.value) } }) } } return rtn } function findValueByCustomId(d, n, c) { let value = "Undefind"; let rtn = value; for (var i = 0; i < d.length; i++) { var item = d[i]; if (item.customId == c) { //console.log(item.customId,c) if (item.values) { //console.log(item.options) item.values.forEach(function (v) { if (v.name == n) { rtn = v.value } }) } } } return rtn }