Prevent Google Event sending when pressed F5 and access via GET

Asked

Viewed 62 times

0

Personal talk!

I need to do a prevention of sending event of analitycs in the following scenario:

I have a form that when Submit is given, the post is processed in ajax and this ajax returns a URL in which I redirect via location.href. This other page where you receive the direction, has the code snippet where you send the event to Google. What happens is that every time the F5 user enters the link directly, the event is being accounted for, giving erroneous results in the Analitycs reports.

Follow an example:

Home Page:

<form id="form">
  <input type="text" name="teste" />
  <button>Processar</button>
</form>

Landing page:

<script>
 // preciso prevenir esse envio quando usuário der F5 ou entrar na página sem passar
 // pelo form
 ga('send', 'event', 'Teste', 'view', '<?php echo $_GET['varTeste'] ?>');
</script>

Script that does the redirect:

$( "#form" ).submit(function() {
  // ajax na qual retorna o link
  url = 'teste.php?varTeste=123';
  location.href = url;
});
  • What’s the $varTeste for?

  • is an id to find the information of that id in the bank

1 answer

1


You could add the script to the DOM only if a specific parameter is present in $_GET.

<?php if (isset($_GET['varTeste'])): ?>
    <script>...</script>
<?php endif ?>

And then you can remove this parameter via Javascript, so when the page was reloaded, or accessed without the parameter the script would not be added to the DOM.

$(document).ready(function () {
    // remove os parametros GET
    window.history.replaceState(null, null, window.location.pathname);
});

Behold replaceState().

If necessary, add a setTimeout() to delay deleting the url parameter.

  • Well, I’m gonna use a variable in the bank to tell me whether to send the tracking or not, but thank you anyway!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.