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

This may or may not be a bug. I cannot really tell.

Problem:

jQuery scripts do not fire onPageChange when the destination is a topic as consistently as they do when the destination is a discovery route.

Basic example script:

      api.onPageChange((url, title) => {
        console.log('the page changed to: ' + url + ' and title ' + title);
        $(".regular>.cooked>p").addClass("foo-class");
      });

Expected result:

On every page loaded, the page title and url are logged to console and every .regular>.cooked>p element gets the class .foo-class added to it.

And this is exactly what happens on initial page load (if topic is accessed via direct url)

As you can see above, every <p> tag has the class .foo-class added to it and the console logs the page information as instructed.


Actual result

If you navigate away from the topic and go back in or if you go visit another topic by clicking a link from within the app (where the content is loaded via the app), the script behaves differently.

The console logs the page information like before, but the jQuery part is not picked up.

notice how the <p> tags don’t have the class .foo-class added even though the console indicates that the script was executed


For the record, here's the full script and I add it to the `` section of the common theme:
<script type="text/discourse-plugin" version="0.8.13">
      api.onPageChange((url, title) => {
        console.log('the page changed to: ' + url + ' and title ' + title);
        $(".regular>.cooked>p").addClass("foo-class");
      });
</script>

I also went through the entire plugin-api.js file and did not find any alternative to onPageChange

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/lib/plugin-api.js.es6

1 Like