Search code examples
javascriptgoogle-tag-manager

how to add URL parameters if the traffic comes from Google Search Engine?


I need to know how to detect if the traffic in the browser comes from Google Search Engine (SEO) programmatically using Google Tag Manager, and then convert it to URL paramaters

so if the user comes to my website from Google Search Engine after typing the keywords, then I need to add URL parameters utm_source=google and utm_medium=organic. so if the user comes from search engine then the URL should be like this

https://myWeb.com/?utm_source=google&utm_medium=organic

how to do that using Google Tag Manager in Javascript?


Solution

  • You normally should have some kind of tag script at the end of your page.

    If not try this. You cannot rely 100% on the referer but this should work in normal circumstances

    const reloadWithUTM = () => {
      const url = new URL(location.href);
      if (!document.referrer.toLowerCase().includes('google')) return; // not google
      if (url.searchParams.get('utm')) return; // already has the tags
      url.searchParams.set('utm_source', 'google');
      url.searchParams.set('utm_medium', 'organic');
      console.log(url.toString()); // test
    //  location.replace(url.toString()); // uncomment when happy
    };
    reloadWithUTM();