WebPal
WebPal

Reputation: 656

How to prevent Google AdWords script from prevent reloading in SPA?

I have a SPA built on React JS stack. I'm using react-router to navigate through pages and i need to implement Google AdWords on my website.

<script type="text/javascript">
  /* <![CDATA[ */
  goog_snippet_vars = function() {
    var w = window;
    w.google_conversion_id = 333333;
    w.google_conversion_label = "33333";
    w.google_remarketing_only = false;
  }
  // DO NOT CHANGE THE CODE BELOW.
  goog_report_conversion = function(url) {
    goog_snippet_vars();
    window.google_conversion_format = "3";
    var opt = new Object();
    opt.onload_callback = function() {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  }
  var conv_handler = window['google_trackConversion'];
  if (typeof(conv_handler) == 'function') {
    conv_handler(opt);
  }
  }
  /* ]]> */
</script>

I embed this code in body and i run goog_report_conversion when i click on button which navigates me to another page. Which is unwanted behaviour for SPA.

<Link
  className="btn btn-primary"
  to="/settings"
  onClick={() => goog_report_conversion('site.name/settings')}
>Go to settings</Link>

The problem is that once I do it, it fully reloads my webpage. I know that this line causes the problem

window.location = url;

But without it script doesn't work.

I also tried to create this event in Google Tag Manager and follow advices given here Google Tag Manager causes full page reload in SPA - React but it didn't help me.

Have anyone faced same problem implementing AdWords in SPA? How did you solve it?

Upvotes: 1

Views: 2031

Answers (1)

dorian
dorian

Reputation: 6272

I feel that the implementation example for the asynchronous Remarketing/Conversion snippet is needlessly complex. Here's something that we used in a similar scenario.

First we define a little helper function that we can reuse:

<script type="text/javascript">
function triggerConversion(conversionID, conversionLabel) {
    if (typeof(window.google_trackConversion) === "function") {
        window.google_trackConversion({
            google_conversion_id: conversionID,
            google_conversion_label: conversionLabel,
            google_remarketing_only: false
        });
    }
}
</script>

then we include Google's async conversion script (ideally somewhere where it doesn't block rendering):

<script type="text/javascript"
        src="http://www.googleadservices.com/pagead/conversion_async.js" 
        charset="utf-8">
</script>

And now you can track conversions on any element, like so, to adapt your example:

<Link
  className="btn btn-primary"
  onClick={() => triggerConversion(333333, "33333")}
>Go to settings</Link>

Upvotes: 3

Related Questions