Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hotwired/turbo support and fixes issue with duplicate events in GTM #160

Merged
merged 3 commits into from
Jul 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
<% if container %>
<% unless options[:turbolinks] %>
<% if events.any? %>
<script>
dataLayer = [];
dataLayer.push(<%= events.map(&:write).join(', ') %>);
</script>
<% end %>
<% end %>

<script>
dataLayer = [];

<% if options[:turbolinks] %>
document.addEventListener('turbolinks:load', function(event) {
var url = event.data.url;
<% if events.any? %>
dataLayer.push(<%= events.map(&:write).join(', ') %>);
<% end %>
dataLayer.push({'event':'pageView','virtualUrl': url});
});
document.addEventListener('turbo:load', function(event) {
var url = event.detail.url;
dataLayer.push({'event':'pageView','virtualUrl': url});
});
<% end %>
</script>

<% if events.any? %>
<script>
<%# Generates unique script tags to ensure that turbo/turbolinks include %>
<%# them in the document even if the same event happens more than once %>
// Unique Script ID: <%= SecureRandom.base64(8) %>
dataLayer.push(<%= events.map(&:write).join(', ') %>);
</script>
<% end %>

<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=
Expand Down
5 changes: 3 additions & 2 deletions spec/integration/google_tag_manager_integration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@
expect(page.find("body")).to have_xpath '//body/noscript/iframe[@src="https://www.googletagmanager.com/ns.html?id=GTM-ABCDEF"]'
end

it "embeds the turbolinks observer if requested" do
it "embeds turbolinks and turbo observers if requested" do
visit '/'
expect(page.find("head")).to_not have_content "turbolinks:load"
setup_app(action: :google_tag_manager) do |tracker|
tracker.handler :google_tag_manager, { container: 'GTM-ABCDEF', turbolinks: true }
end
visit '/'
expect(page.find("head")).to have_content "turbolinks:load"
expect(page.find("head")).to have_content "turbo:load"
end
end
end