Skip to content

Instantly share code, notes, and snippets.

@prabapro
Created September 1, 2020 16:33
Show Gist options
  • Save prabapro/2352125f3ba84c5b993d0636fe12b244 to your computer and use it in GitHub Desktop.
Save prabapro/2352125f3ba84c5b993d0636fe12b244 to your computer and use it in GitHub Desktop.
GTMTips: Prevent Clicks And Form Submits From Redirecting - Bookmarklet

GTMTips: Prevent Clicks And Form Submits From Redirecting

Extracted from Simo Ahava's Blog Post

Using Custom beforeunload script

Google Tag Manager offers us some nice built-in triggers so that we can automatically listen for specific user interactions on the website, reacting to them however we wish, though typically it would be to fire a tag. The tricky thing especially with the click triggers and form submission tracking is that the page has a nasty habit of redirecting you to the link or form target page before letting you see the respective data in Google Tag Manager’s excellent preview mode.

This solution should work with all redirects regardless of how they’re implemented. The trick is to add an event listener to the beforeunload browser, opening a prompt that asks if you really want to leave the current page. You can then press “Cancel” (or equivalent) to stay on the current page to see what the browser event wrote into dataLayer. To do this, you need to open the JavaScript console in the browser and copy-paste the following code, pressing enter when done:

window.addEventListener('beforeunload', function(e) {
  e.preventDefault();
  e.returnValue = '';
});

Now when submitting the form or clicking a link, a prompt should pop up and you can press Cancel to see the Preview mode output.

Achieve this via Chrome Bookmarklet

Create a new Bookmarklet with using below url;

javascript:window.addEventListener%28%27beforeunload%27%2C%20function%28e%29%20%7B%0A%20%20e.preventDefault%28%29%3B%0A%20%20e.returnValue%20%3D%20%27%27%3B%0A%7D%29%3B

Now click on your bookmarklet once & press your form submit button or links.

Screenshot: https://prnt.sc/u9q96f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment