How do you run jQuery in preview window?

bmamlin March 6, 2015

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
})
-->
</script>

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.

Cheers,

-Burke

Update:

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
  myFunction(AJS.$(document))
})
AJS.bind("init.rte", function() {
  // When previewing, apply changes
  AJS.Editor.previewFrameOnload = (function(oldFunc) {
    return function(body, iframe) {
      myFunction(AJS.$(body))
      oldFunc.apply(AJS.Editor, arguments)
    }
  }(AJS.Editor.previewFrameOnload))
})
-->
</script>

1 answer

1 accepted

0 votes
Answer accepted
Stephen Deutsch
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
March 6, 2015

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.

bmamlin March 6, 2015

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
TAGS
AUG Leaders

Atlassian Community Events