0

I just want a function to run whenever a new page is created in inDesign. Adobe's documentation appears to let you attach event handlers to nearly all objects, but they don't give any examples of how to do this past the document level.

var myEventListener = app.eventListeners.add("afterNew", myAfterNewHandler);

How do I get this to trigger on creation of a new page. I've already tried replacing app with app.document.pages and it did not work.

Uncle Slug
  • 853
  • 1
  • 13
  • 26

3 Answers3

2

Try this…

#targetengine 'onAddingPage'

var db = {};

var main = function () {
 var myIdleTask = app.idleTasks.item ("onAddingPage"),
 onIdleEventHandler = function(idleEvent) {
  var doc = app.properties.activeDocument;
  
  if ( !doc ) {
   db = {};
   return;
  }
  
  if ( !db[doc.id] ) {
   db[doc.id] = doc.pages.length;
   return;
  }
 
  else {
   if ( doc.pages.length>db[doc.id] ) {
    !app.modalState && alert("Hey you just added "+(doc.pages.length-db[doc.id])+" page(s) ! Didn't you ?" );
   }
   db[doc.id] = doc.pages.length;
  }
 };
 
 if(!myIdleTask.isValid) {
  myIdleTask = app.idleTasks.add({name:"onAddingPage", sleep:100});
  myIdleTask.addEventListener(IdleEvent.ON_IDLE, onIdleEventHandler);
 }
}

main();

Adding pages through menu item

Reacting on adding pages Event

Loic
  • 2,173
  • 10
  • 13
1

I tried to use MutationEvent, this snippet creates textframe with timestamp on adding new page.

#targetengine session

var doc = app.activeDocument;
var listener = doc.addEventListener(
  MutationEvent.AFTER_ATTRIBUTE_CHANGED,
  create_dummy
);
listener.name = 'ooo';

function create_dummy(e) {
  if (e.attributeValue.constructor.name === 'Page') {
    var tf = e.attributeValue.textFrames.add();
    tf.geometricBounds = [1,1,72,144];
    tf.parentStory.contents = new Date().toString();
  }
}

thank you

mg

milligramme
  • 404
  • 3
  • 9
  • This solution worked. However it also runs the function when the page is deleted or the page is double clicked in the pages panel. Is there any way to differentiate between those other events? – Uncle Slug Apr 30 '16 at 17:33
1

I couldn't find any smart way.

following snippet works only with adding new page icon in page panel or it's shortcut,

setting page length in document setting dialog cause modal dialog error.

var doc = app.activeDocument;
var p = doc.pages.length;
var listener = doc.addEventListener(
  MutationEvent.AFTER_ATTRIBUTE_CHANGED,
  create_dummy
);
listener.name = 'ooo';

function create_dummy(e) {
  if (e.attributeValue.constructor.name === 'Page') {
    if (p < e.currentTarget.pages.length) {
      var tf = e.attributeValue.textFrames.add();
      tf.geometricBounds = [1,1,72,144];
      tf.parentStory.contents = e.timeStamp.toString();
    }
    p = e.currentTarget.pages.length;
  }
}

thank you

mg

milligramme
  • 404
  • 3
  • 9