How do you force a script to refire on every page load in Discourse?

Alright, here’s one more update on this. I think I maybe on to the reason why api.onPageChange does not work for topic pages and the answer might be this:

With that in mind here’s the new way I settled on for firing a script once a user enters a topic page and doing a bit of clean up after leaving the topic page. This could still be improved I suppose but for now will only fire once when entering a topic and once when leaving.

const TopicRoute = require('discourse/routes/topic').default;

TopicRoute.reopen({
	activate: function() {
		this._super();
		Em.run.next(function() {
		// do stuff here when a topic page is opend
		});
	},
	deactivate: function() {
		this._super();
		// clean up here when leaving the topic page
	}
});

As far as I tested, this will both log stuff to the console and work with jQuery. edit: Nope. Again :sweat_smile:

If anyone is interested in the breadcrumbs I came accross to put this together check these posts / topics out:

breadcrumbs

https://meta.discourse.org/t/accessing-the-createtopic-action-while-on-a-topic-route/26423

A tour of how the Widget (Virtual DOM) code in Discourse works

https://meta.discourse.org/t/using-jquery-to-add-a-link-to-a-group-badge/40563

https://meta.discourse.org/t/customizing-the-home-screen-to-show-tiles-for-topics/16713/2

https://meta.discourse.org/t/how-to-insert-static-welcome-text-block-on-categories-page/16090/5

https://meta.discourse.org/t/wip-list-of-all-the-hooks-in-discourse/11505

A tour of how the Widget (Virtual DOM) code in Discourse works

Once I figure out how to fire a script once every time the post stream is updated I will post another update here.

3 Likes