Last active
February 19, 2026 10:20
-
-
Save mrl22/673c2170019ef3c41ddef12136405876 to your computer and use it in GitHub Desktop.
Livewire v3 and v4 - Redirect all internal links via wire:navigate (removes requirement to add wire:navigate to all links)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| document.addEventListener('click', (event) => { | |
| const link = event.target.closest('a'); | |
| if (!link) return; | |
| // Modified clicks (new tab, etc) | |
| if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; | |
| // Already handled by Livewire | |
| if (link.hasAttribute('wire:navigate')) return; | |
| const href = link.getAttribute('href'); | |
| if (!href) return; | |
| // Cheap string-based exits first | |
| if ( | |
| href[0] === '#' || | |
| href.startsWith('mailto:') || | |
| href.startsWith('tel:') || | |
| link.hasAttribute('download') || | |
| link.target === '_blank' | |
| ) { | |
| return; | |
| } | |
| // Single attribute scan | |
| for (const { name } of link.attributes) { | |
| if ( | |
| name.startsWith('x-on:click') || | |
| name.startsWith('@click') || | |
| name.startsWith('wire:click') | |
| ) { | |
| return; | |
| } | |
| } | |
| // Resolve URL only when needed | |
| let url; | |
| try { | |
| url = new URL(href, window.location.origin); | |
| } catch { | |
| return; | |
| } | |
| // External or same-page links | |
| if ( | |
| url.origin !== window.location.origin || | |
| url.pathname === window.location.pathname | |
| ) { | |
| return; | |
| } | |
| event.preventDefault(); | |
| Livewire.navigate(url.href); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment