How do you run jQuery in preview window?

I've got a script set up to run on every page using Custom HTML in Confluence:

<script type="text/javascript">
AJS.toInit(function() {
  console.log('This displays on page render, but not when previewing.')
  // Use AJS.$ for jQuery code here

It works as expected when viewing pages, but the script is not invoked in the preview window.  I'm inferring AJS.toInit() is only called when a page is rendered and not during previewing from the editor.

Is there a proper way to invoke a custom jQuery script like this that will be run both when pages are rendered and when the page is previewed from the editor?

I've scanned documentation, but haven't yet found an answer to this question.  Any help would be appreciated.




From @Stephen Smith's answer, I realized that AJS.toInit() is only invoked when the page is loaded and the page isn't reload when previewing. That led me to find AJS.Editor.previewFrameOnLoad and the AJS.bind("init.rte", function() { ... }) tip. So, I ended up with something like:

<script type="text/javascript">
function myFunction(elem) {
  // do something to the given HTML element
AJS.toInit(function() {
  // When page loads, apply changes
AJS.bind("init.rte", function() {
  // When previewing, apply changes
  AJS.Editor.previewFrameOnload = (function(oldFunc) {
    return function(body, iframe) {
      oldFunc.apply(AJS.Editor, arguments)

1 answer

1 accepted

0 votes
Accepted answer

Hi Burke,

I think it's not that AJS.toInit is not invoked in the preview window, but that the Custom HTML is not invoked in the preview window.  Not sure how you could fix that one... If you are using the documentation theme, then you could put your javascript in a user macro and embed it in every page using the custom theme options, but I'm still not sure if it would run in the preview window.  Your best bet would probably be to modify the page decorators, but maybe someone else could comment on that, since I'm not so familiar with it.

Thanks @Stephen Deutsch! Your response led me down the path to a solution. Since comments don't support formatting, I'll update my question with the solution that you nudged me to. Thanks!

Suggest an answer

Log in or Sign up to answer
Community showcase
Published yesterday in Agile

How Scrum works? It starts with training and education

To answer “How scrum works,” most of the teams I've worked with first addressed the question: “where to start?”  That question applies to both implementation and improvements on the Scrum framew...

167 views 3 5
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you