Core Method: Link Modification via TextFormatter (PHP)
By leveraging Flarum’s TextFormatter, we can modify links on the backend before they are served. This ensures 100% compatibility with the SPA (Single Page Application), eliminates client-side lag, and provides better indexing for search engines.
Supplementary Method (Fallback): Frontend Script Injection
Include the platform’s JS script in the header via Extend\Frontend. This should only be used as a fallback if the service strictly requires it for tracking or analytics purposes.
SPA Triggering
To ensure the script "sees" new posts loaded via infinite scroll, we must use extend on Post.prototype.oncreate. This allows the script to process new content dynamically as it enters the DOM.
Verdict
Your proposed solution is functional, but I recommend shifting the focus from "intercepting links via JS" to "pre-processing links via PHP." This approach elevates the extension from a simple "patch" to a professional-grade integration.
- Leveraging the Post Component Hook
In Flarum, every post is an object. We can extend the oncreate (or onupdate) method of the Post class to handle dynamic content.
Code Snippet (JavaScript):
JavaScript
extend(Post.prototype, 'oncreate', function() {
// This code executes whenever a post is rendered in the DOM
// Trigger the API re-initialization specifically for this post element
if (window.linkvertiseAPI) {
window.linkvertiseAPI.scan(this.element);
}
});
SPA Routing Fix
Instead of relying on window.onload, we could subscribe to app.history.push. However, by utilizing the Post.oncreate hook, manual router subscriptions become unnecessary. The posts will automatically "notify" the script as soon as they are mounted in the UI.
Admin Configuration Options
To make the extension user-friendly, the admin panel should include:
User ID / API Key Field: A dedicated input for the user's platform credentials.
Domain Whitelist/Blacklist: Settings to prevent the script from converting internal forum links or specific trusted domains into monetized links.
Scope Toggle: An option to choose between "Process posts only" or "Process all content (including user profiles and signatures)."