1. function collectQueryStringMetrics() {
  2. const metrics = {};
  3. // Function to extract and process a query string parameter
  4. function processQueryString(key, value) {
  5. if (key && value) {
  6. // Sanitize key and value (optional, but recommended)
  7. const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, '_'); // Replace invalid chars with underscore
  8. metrics[sanitizedKey] = {
  9. count: (metrics[sanitizedKey] || 0) + 1,
  10. values: metrics[sanitizedKey].values || [],
  11. };
  12. metrics[sanitizedKey].values.push(value);
  13. }
  14. }
  15. // Get the query string parameters
  16. const queryString = window.location.search;
  17. if (queryString) {
  18. const params = queryString.split('&');
  19. for (const param of params) {
  20. const [key, value] = param.split('=');
  21. processQueryString(key, value);
  22. }
  23. }
  24. return metrics;
  25. }
  26. // Example usage (you'll need to adapt this to your environment)
  27. const metrics = collectQueryStringMetrics();
  28. // Log the metrics (or send them to a server)
  29. console.log(metrics);
  30. // Optionally, you can implement a periodic reporting mechanism
  31. // setInterval(() => {
  32. // console.log("Metrics at:", new Date());
  33. // console.log(metrics);
  34. // }, 60000); // Log every minute

Add your comment