optinmonster.js
70 lines
| 1 | (function () { |
| 2 | function isOptinMonsterSubmitUrl(url) { |
| 3 | if (!url) { |
| 4 | return false; |
| 5 | } |
| 6 | |
| 7 | try { |
| 8 | const u = new URL(url, window.location.href); |
| 9 | return u.hostname === "api.omappapi.com" && u.pathname.startsWith("/v2/optin/"); |
| 10 | } catch (e) { |
| 11 | return false; |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | function getFormId(url) { |
| 16 | const match = url.match(/\/optin\/([^/?#]+)/); |
| 17 | return match ? match[1] : null; |
| 18 | } |
| 19 | |
| 20 | function forwardToWP(formId, data) { |
| 21 | if ( |
| 22 | !data || |
| 23 | !window?.hostinger_reach_optinmonster_data?.nonce || |
| 24 | !window?.hostinger_reach_optinmonster_data?.restUrl) { |
| 25 | return; |
| 26 | } |
| 27 | const payload = JSON.parse(data); |
| 28 | fetch(window.hostinger_reach_optinmonster_data.restUrl, { |
| 29 | method: "POST", |
| 30 | headers: { |
| 31 | "Content-Type": "application/json", |
| 32 | "X-WP-Nonce": window.hostinger_reach_optinmonster_data.nonce |
| 33 | }, |
| 34 | body: JSON.stringify({...payload, formId}), |
| 35 | credentials: "same-origin", |
| 36 | }).catch(function () { |
| 37 | console.error("Failed to forward OptinMonster data to Reach"); |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Patch XHR request from OptinMonster to forward a copy to WP |
| 43 | * to send it to Reach. |
| 44 | **/ |
| 45 | const OriginalXHR = window.XMLHttpRequest; |
| 46 | if (!OriginalXHR) return; |
| 47 | window.XMLHttpRequest = function () { |
| 48 | const xhr = new OriginalXHR(); |
| 49 | |
| 50 | let requestUrl = ""; |
| 51 | const originalOpen = xhr.open; |
| 52 | xhr.open = function (method, url) { |
| 53 | requestUrl = String(url || ""); |
| 54 | return originalOpen.apply(this, arguments); |
| 55 | }; |
| 56 | const originalSend = xhr.send; |
| 57 | xhr.send = function (body) { |
| 58 | if (isOptinMonsterSubmitUrl(requestUrl)) { |
| 59 | forwardToWP(getFormId(requestUrl), body); |
| 60 | } |
| 61 | |
| 62 | return originalSend.apply(this, arguments); |
| 63 | }; |
| 64 | |
| 65 | return xhr; |
| 66 | }; |
| 67 | |
| 68 | window.XMLHttpRequest.prototype = OriginalXHR.prototype; |
| 69 | })(); |
| 70 |