Last active
September 6, 2022 00:21
-
-
Save mbaersch/d1df56d00d9b0da0db2702dc0c212a9f to your computer and use it in GitHub Desktop.
Tampermonkey script to add a new section to the GA4 Event Builder for sending payloads to a custom endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Enhance GA4 Event Builder | |
// @namespace http://tampermonkey.net/ | |
// @version 0.2 | |
// @description add option to send payload to a custom endpoint instead of google-analytics.com | |
// @author Markus Baersch | |
// @match https://ga-dev-tools.web.app/ga4/event-builder/ | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
// Your code here... | |
window.onload = function(){ | |
var d = document.createElement("div"); | |
var di = document.createElement("div"); | |
var h = document.createElement("h3"); | |
h.className = "MuiTypography-root jss43 MuiTypography-h3"; | |
h.innerHTML = 'Custom Endpoint'; | |
di.className = "MuiPaper-root MuiCard-root jss24 jss74 MuiPaper-elevation1 MuiPaper-rounded"; | |
var i = document.createElement("input"); | |
i.style.width = '90%'; | |
i.style.padding = '3px'; | |
i.style.marginBottom = '1em'; | |
i.value = window.localStorage.getItem("post_endpoint") || 'https://myendpoint.domain.com/mp/collect?api_secret=xxxxxxxxx&measurement_id=G-yyyyyyy'; | |
i.id="mep_ep"; | |
var b = document.createElement("input"); | |
b.type = 'button'; | |
b.value = 'SEND PAYLOAD TO CUSTOM ENDPOINT'; | |
b.className = 'MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-containedPrimary'; | |
var jsonpayload; | |
b.addEventListener('click', function() { | |
if (!jsonpayload) { | |
console.error('Payload Feld nicht gefunden!'); | |
return; | |
} | |
var obs = jsonpayload.innerText.replace(/(([a-zA-Z"\]}])(\n))/gm, "$2,").replace(/\n/g, "").replace(/,(\]|})/g, "$1"), | |
ep = i.value; | |
window.localStorage.setItem("post_endpoint", ep); | |
if (navigator.sendBeacon) navigator.sendBeacon(ep, obs); | |
else { | |
if (window.XMLHttpRequest) var req = new XMLHttpRequest(); | |
if (req != null) { | |
req.open("POST", ep, true); | |
req.setRequestHeader("Content-Type", "text/plain"); | |
req.send(obs); | |
} | |
} | |
}); | |
di.appendChild(i); | |
di.appendChild(b); | |
d.appendChild(h); | |
d.appendChild(di); | |
var f = document.querySelector("main section:first-child"); | |
window.setTimeout(function(){ | |
jsonpayload = document.querySelector("div.react-json-view"); | |
if (jsonpayload) f.appendChild(d); | |
}, 5000) | |
}; | |
})(); |
Author
mbaersch
commented
Aug 11, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment