'Turbo Drive not intercepting links (but turbo:load event fires)
I'm experimenting with adding Turbo to a Rails 6.1 app.
It seems to be loading (see "What I've tried"), but when clicking around the clicks does not seem to be intercepted. I'm still getting full page reloads.
Can anyone help me spot what is missing here?
What I've tried
- Added an event handler with console.log() output that shows that the
turbo:load
is indeed getting triggered - Ensured
Turbo.session.drive = true
inapplication.js
- Even tried adding
data-turbo="true"
to a<main>
tag, but that seems to have made no difference. Perhaps not too surprising, given pt. 2. - Firefox and Chrome
Setup
// app/javascript/application.js
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = true
# config/importmap.rb
pin 'application', preload: true
pin '@hotwired/turbo-rails', to: 'turbo.js'
// Debugging statement
document.addEventListener('turbo:load', function() {
console.log('turbo:load');
})
Solution 1:[1]
So I found out that the mere inclusion of the Google Analytics 4 script tag in <head>
caused Turbo not to work:
<script async src="https://www.googletagmanager.com/gtag/js?id=<OUR ID>"/>
The reason? GA4's automatic outbound link click tracking, which we have enabled. There's a very recent Github issue about this. As mentioned in a comment:
"... seems like they call preventDefault on link-click events, even if it's not an outbound click. Turbo then decides it's not a significant event so allows the navigation to go ahead as normal"
I disabled this feature in GA4, and was good to go.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |