framework
framework copied to clipboard
Canonical URL remains when navigating between pages
Current Behavior
When navigating through the SPA, the canonical found in the page <head>
remains.
E.g., if you visit the forum home page, then navigate to a discussion, the canonical is still the home page URL.
Steps to Reproduce
Self-explanatory
Expected Behavior
Canonical should be updated with a new URL
Screenshots
No response
Environment
- Flarum version: 1.5.0
- Website URL: [local]
- PHP version: 8.1.x
Output of php flarum info
No response
Possible Solution
No response
Additional Context
No response
In a project I'm working on, I've implemented this hack:
const oldPushState = window.history.pushState;
window.history.pushState = function (...args) {
oldPushState.call(this, ...args);
document.head.querySelectorAll('link[rel="canonical"]').forEach((link) => {
if (link.getAttribute('href') !== window.location.href) {
link.setAttribute('href', window.location.href);
}
});
document.head.querySelectorAll('link[rel="next"], link[rel="prev"]').forEach((link) => {
link.remove();
});
};
I always assumed it was by design. That attribute is only for the initial page load / scrapers, just like if OpenGraph data is added to the page.
I'm not sure how we can refresh this kind of data without making an API request that involves the Content
classes on each page change.
Setting the canonical
on page change without retrieving the right canonical URL seems like it might create more issues than solutions? The URLs generated client-side by the SPA are not guaranteed to be canonical.
Removing the tag after the first URL change does seem to make the most sense if it's interfering with JS libraries. Libraries can then fall back to the current browser URL which isn't guaranteed canonical.
The reason I ran into this issue was that some analytics providers utilise the canonical, if present, instead of the actual URL, like Fathom.
I wonder if we should remove it (and rel=prev/next) on navigation, but perhaps an extension could be better placed for updating it (perhaps somehow with a "get canonical" API endpoint?).
Not sure about the best approach here.