Extracting Search term via URL Frgments

Posted by: JP Betis Date Posted: December 12, 2024
Back to Case Studies

Issue

An Architect reach out to me via SME queue asking for help on how to track a search term and add it as an event for LMFX micro conversions on MCFX. She initially followed the step by step procedure on how to track a conventional Site Search event using the dedicated Guru card for Site search events but later realized that the variable script doesn’t seem to work and keeps on returning a null or invalid character.

Solution

Upon further checking and testing, I noticed that the search term populates together with the URL fragments (a very long line of URL). A fragment is an internal page reference, sometimes called a named anchor. It usually appears at the end of a URL and begins with a hash (#) character followed by an identifier. It refers to a section within a web page.

From there on, it came to me that I need to consider looking at this issue on a different angle and able to provide a solution on a different perspective. So I did some research and tried several script revision until I came up with a most suitable solution that will capture the search term without a fuzz.

Here’s the custom JS I created

function() {
try {
var hash = window.location.hash;
var decodedHash = decodeURIComponent(hash);
var jsonStart = decodedHash.indexOf('{');
var jsonEnd = decodedHash.lastIndexOf('}') + 1;
var jsonString = decodedHash.substring(jsonStart, jsonEnd);
var jsonObj = JSON.parse(jsonString);
return jsonObj.map.search || 'No search term found';
} catch (e) {
return 'Error parsing search term';
}
}

Another problem I noticed is that the search box doesn’t seem to refresh or redirect the page once the search button has been pressed (uses AJAX to load the page content without completely loading the whole webpage), so instead of using a “Pageview” as a trigger, I used “History Change” trigger.

 

Achievement

I was able to create a new GTM variable that will capture search terms via URL fragments

Snippet/Screenshot/Link

GTM Tag: https://webpagefx.mangoapps.com/msc/MjA3OTEwM18xNDMxODE1MA

GTM Trigger: https://webpagefx.mangoapps.com/msc/MjA3OTEwNV8xNDMxODE1Mg

GTM Variable: https://webpagefx.mangoapps.com/msc/MjA3OTEwOF8xNDMxODE1NQ

Related Guru: https://app.getguru.com/card/irBBjpqT/Tracking-Site-Search-Results-in-GTM-as-a-LeadManagerFX-Event?query=site+search