Load Google Tag Manager Synchronously - tracking

I have searched Google Tag Manager (GTM) documentation and did not find anything addressing this issue. I'm working with an affiliate network who wants their tracking pixel to be loaded synchronously to ensure that it fires before the content of the page loads. This only applies to our order confirmation page. We've implemented GTM so we can launch and fix tags in 5 minutes versus 2 weeks.
GTM is installed at the top of our order confirmation page and loads tags asynchronously so I know that the affiliate networks' tags are loading very quickly but the networks are still concerned that some data may be lost. GTM doesn't have any options or documentation that would indicate that it is possible to load the script synchronously but I notice the j.async=true name-value pair in their code.
If I change that part of the code to j.async=false, will the code load synchronously or will I just break it?
Here's the full code for reference.
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','myNewName','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

The article on Cardinal Path is great for learning how to setup synchronous tags.
However, as for the concern about ensuring there is no lost data, I would like to highlight Mickael's comment at the bottom of that article. Since the dataLayer.push might not be complete before the gtm.dom event occurs, you should include a custom event in the dataLayer.push so you are not relying on gtm.dom to fire your tags.
Here is an example tag with a custom event specific to page load.
Tag Name: pageLoad
Tag Type: Custom HTML Tag
HTML:
<script type="text/javascript">
var tid = setInterval( function () {
if ( document.readyState !== 'complete' ) return;
clearInterval( tid );
dataLayer.push({ "event": "pageLoaded" });
}, 100 );
</script>
Add the following Firing Rule.
Rule Name: All pages
Condition: {{url}} matches RegEx .*
Then, on the affiliate tags you want fired, all you have to do is include this custom event (i.e. pageLoaded) as a condition on the firing rule. In this example, the condition would be: {{event}} equals pageLoaded

We had a similar requirement with regards to defining a page type and then operating a rule/macro based on that input.
The suggestion I found was to have a rule in GTM to determine pageload/rule load etc.
I found it in this article, http://www.cardinalpath.com/controlling-tag-firing-order-with-google-tag-manager/
Hopefully that will help solve it - in theory you should be able to, have something that will trigger the GTM code before the page load.

Related

Multi-web server ajax callback with refresh on Enter

Question about how to send a jQuery callback with an onSuccess: refresh from a textInput when the user presses [Enter]. We use the [Enter] press to trigger a search callback.
Our GS Seaside app uses HAProxy. This means the onSuccess: script is handled by a different gem than the one that handles the callback. Because of this, users will sometimes get the refresh because the callback, which to them looks like a lost input (a browser F5 refresh shows the right state). If running single gem or in a VW / Pharo image this problem does not come up.
I can work around the problem by using...
async: false;
...but that prevents me from show any kind of waiting feedback (I normally use a busy gif).
So, the question is: in a multi-web server configuration, how can you code a callback to...
1 - show a busy gif
2 - trigger the search callback
3 - refresh the display when done
...all in that order.
Using a form submission callback is a problem because multiple text inputs can trigger the search, since the callback is 'set value + do search', by virtual of the default [Enter] press.
For the JS callback, I'm using...
self onKeyPress: (
(JSStream
on: '(window.event ? window.event.keyCode : event.which) == 13')
then: (canvas jQuery ajax callback: aBlock value: canvas jQuery this value))
It all works fine, except for the missing busy gif, due to the 'async: false'.
Any suggestions?
You can define a beforeSend and a complete handler to show and hide the loading indicator while the request is being processed. The global parameter set to false is meant to ignore your existing handlers to process request start and end (the mentioned spinner), and only use these defined in the particular instance of the JQAjax object.
((html jQuery ajax)
async: false;
global: false; "https://api.jquery.com/category/ajax/global-ajax-event-handlers/"
callback: aBlock value: canvas jQuery this value;
onBeforeSend: (html jQuery id: 'indicator') show;
onSuccess: ((html jQuery id: 'fieldId') load html: [:h | ]);
onComplete: (html jQuery id: 'indicator') hide;
That said, keep in mind that doing a synchronous AJAX call is discouraged since it will block the whole UI thread until the request is resolved.
So it's not completely clear how you manage the state in different worker images (gems, in this case) returning different things (probably because of having different sessions), so it's also not clear to me why doing an async XHR request will be served differently to doing it synchronously, I never experienced that.
From the small sample you mention, it can't be deduced what is the "refresh" part of your code. So maybe, providing more context will help us give you more accurate answers.
Fix ended up being trivial: needed to include 'event.preventDefault();' in the [Enter] key script. Seems obvious in hindsight.
if ((window.event ? window.event.keyCode : event.which) == 13) {
event.preventDefault();
};'
This problem is confirmed to be a narrow configuration symptom: GemStone with multiple gems. On every other configuration Seaside / javascript behaves as expected. I will follow this up as a vendor problem. Thanks to everyone that looked at it (this was also posted on other forums).

submit button not working when generated from AJAX

I got an ASP NET Core RazorPage having a button which asynchronously replaces a part of the given HTML using an AJAX request.
Besides some text content it renders another button which is intended to post back the side when clicked. It is surrounded by a form element.
However, clicking the button I receive an HTTP 400 with the information "This page isn't working" (Chrome). Other browsers like Firefox return an HTTP 400 as well.
The relevant HTML with the button which has been created by the AJAX call is the one below:
<form method="post">
<button class="btnIcon" title="Todos" id="btnTodos" formaction="PersonManagement/Parts/MyPageName?handler=PerformTodos">Execute action</button>
</form>
As the url exists (I doublechecked it using the browser with a simple GET) I wonder whether the issue could be due to some security settings along with the browser or is there anything I am perhaps missing out here?
Thank you for any hint
Two things here first add this attribute to your form asp-antiforgery="true", then send it's value to the server in your AJAX post request.
jQuery magic starts here :)
token: $('[name=__RequestVerificationToken]').val(),
Antiforgery is ON by default since .net core 2.0 (as far as I remember), so if you do AJAX post you need to send the antiforgery token with each request.
Let us know if it helps. Spread knowledge don't hide it just for yourself :P
Finally I came across a very interesting article from Matthew Jones at https://exceptionnotfound.net/using-anti-forgery-tokens-in-asp-net-core-razor-pages/ about Anti-Forgery Tokens in Razor pages. Worth reading, indeed.
However, independently from that article what solved my issue was simply not to add the <form .. element at the client-side, but already at the server-side. As there is no need for me to explicitly adding it at the client-side, but only the button itself, this is a solution for me which works properly.
A brief summary of my scenario now:
There is a Razor Page containing usual cshtml content along with a <form method="post"..
Some anchor elements also are included, one is triggering a JQuery AJAX call to the server
The JQuery call comes back from the server with some additional HTML including the post button which which I add to the existing HTML.
The button is being rendered inside the now already existing
Clicking the button causes the page to post back in the wanted manner and executes the handler as intended.
Thanks again Stoyan for your input and help with that.

Blocking some GTM tags when running TestCafe tests - use the dataLayer?

Wondering the best way to prevent a GTM tag from firing. I found https://rbardini.com/automating-gtm-data-layer-tests/ which tags about fetching the dataLayer variable and comparing it in an assertion, but this looks like a clumsy approach when you want to write to the dataLayer on every page.
For example, it suggests:
const getDataLayer = ClientFunction(() => window.dataLayer)
We use Google Tag Manager to automatically load tags on our website. Unfortunately one of them is CloudIQ (from PayPal) which pops up an iframe overlay offering a newsletter signup or ability to save your shopping basket. The Trigger in our GTM setup for that tag is simply 'All Pages'. When it pops up it generally blocks our test because Selectors cannot be clicked.
Our page flow is over several pages of an online shop, e.g.:
visit home page, click a product - navigates to a product page
click some options on the product page, then add to cart
go through checkout flow
So there might be many pages visited due to click actions.
There is an ability in GTM to define Variables and then use them in Exceptions for a tag, so I could prevent the CloudIQ tag firing either via a/ a global variable or b/ a dataLayer variable. However, I can't see how to elegantly get these set for each page visited during my test, such that they would exist when the GTM examines variables in order to block a Tag from being loaded. Fixture.beforeEach isn't right because it would only run once per fixture, and any data it set on the page's scope would be lost as soon as a page navigation occurs.
Anyone got experience of this sort of thing?
(The alternative of course is to detect the overlay, use switchToIframe to switch into the CloudIQ iframe and close it manually, but it pops up quite erratically and I'd prefer to simply disable the Tag altogether during tests as it's not core functionality of our website that we need to test.)
One way would be to set a custom user agent string to your test suite, create a custom javascript variable that returns the value for navigator.useragent, and make an exception trigger that blocks the tag.
Or any variation on that theme - set a cookie, use a url parameter, or if you test suite allow inject a global js variable, and check for the value in an exception trigger.
There is no need to avoid firing of events on the client side. Just mock the service routes for Google Tag Manager and CloudIQ and imitate correct responses for them.

The inner mechanism of WP SEO plugins

This is more of a conceptual question, but it has actual ramifications.
Going through the various SEO plugins I found nowhere a PHP tag that should be embedded in the actual HTML page and echo the meta data. How does it work then?
Simply saving it to the DB doesn't seem enough. What is the mechanism through which the plugin "injects" the SEO data to the page? and what if I have my own meta tag in the page - Would it override the plugin?
The mechanisms are usually FILTERS and ACTIONS hooks from the wordpress Plugin API
This is not particular to the SEO plugins, but to almost all the plugins that change actual content .
simply put :
Action Hooks
Actions Hooks are designs to be used when WordPress core itself, some plugin or theme is giving you a special "breakpoint" to insert your code in order to do some action, or change something while a certain action is triggered .
Filter Hooks :
Filter Hooks are very similar to Action Hooks but what they do is to receive a value and potentially return a modified version of that value.
UPDATE I
see this simple example (put in your themeĀ“s function.php
add_filter( 'the_content', 'my_the_content_filter' );
function my_the_content_filter(){
echo ':::::: THIS CONTENT WILL BE ADDED TO ANY POST :::::';
}
or this :
add_filter( 'the_title', 'my_the_title_filter' );
function my_the_title_filter(){
echo ':::::: THIS CONTENT WILL BE ADDED TO ANY TITLE :::::';
}
UPDATE II
IF however, your question is actually about how SEO works, and not the plugin itself :
SEO is a big subject, but simply put , it is about the meta-tags, titles, descriptions, links, rels etc ... this is what the SEO plugins are changing .
They change things like -
adding automatic descriptions and titles to images
changing page titles
adding meta tags by post
etc etc...
.. - but they all use the above mentioned mechanism of actions and filters hooks. the fact that you do not see it in the code, is that you do not know what to look for .
Try to save the page source BEFORE and AFTER the plugin activation, and then do a diff on both. You will see the differences ...

PrestaShop - Reload CMS page with additional parameters

Situation: I needed to add form with POST method to CMS page. I created custom hook and a module displaying the form successfully. Then I need to react to user input errors eg. when user doesn't enter email address I need to detect it, display the whole page again together with the form and with "errors" in user input clearly stated.
Problem: The problem is to display the WHOLE page again with connected information (eg. about errors etc.). In the module PHP file when I add this kind of code,
return $this->display(__FILE__, 'modulename.tpl');
it (naturally) displays ONLY the form, not the whole CMS page with the form.
In case of this code,
Tools::redirectLink('cms.php?id_cms=7');
I can't get to transfer any information by GET neither POST method.
$_POST['test'] = 1;
Tools::redirectLink('cms.php?id_cms=7&test');
I tried to assign to smarty variables too
$smarty->assign('test', '1');
(I need to use it in .tpl file where the form itself is created) but no way to get it work.
{if isset($test)}...,
{if isset($smarty.post.test)}...,
{if isset($_POST['test'])}... {* neither of these conditionals end up as true *}
Even assigning a GET parameter to url has no impact, because there is link rewriting to some kind of friendly url I guess, no matter I included other argument or not. ([SHOPNAME]/cms.php?id_cms=7&test -> [SHOPNAME]/content/7-cmspage-name)
My question is: is there a way to "redirect" or "reload" current page (or possibly any page generally) in prestashop together with my own data included?
I kind of explained the whole case so I'm open to hear a better overall solution than my (maybe I'm thinking about the case in a wrong way at all). This would be other possible answer.
The simplest method would be to use javascript to validate the form - you can use jQuery to highlight the fields that are in error; providing visual feedback on how the submission failed. In effect you don't allow the user to submit the form (and thus leave the page) until you're happy that the action will succeed. I assume that you will then redirect to another page once a successful submission has been received.
There's lots of articles and how-tos available for using javascript, and indeed jQuery for form validation. If you want to keep the site lean and mean, then you can provide an override for the CMS controller and only enqueue the script for the specific page(s) you want to use form validation on.
If the validation is complex, then you might be best using AJAX and just reloading the form section of your page via a call to your module. Hooks aren't great for this kind of thing, so you might want to consider using an alternative mnethod to inject your code onto the cms page. I've written a few articles on this alternative approach which can be found on my prestashop blog