Skip to main content
Known Participant
October 6, 2023
Answered

Adding Cross reference for foundText

  • October 6, 2023
  • 1 reply
  • 1207 views

Hi Everyone,

 

I need a help with this. I am trying to add crossReference to the text selection on the page, script will find the selected entries inside the text and will add PageNumber CrossReference. But it doesn't iterates the last entry.

 

Throws 'Object is invalid.' error. Can't find what is wrong with this. Please check and help me find what's wrong with this. Please refer the screenshots attached.

 

var myDoc = app.activeDocument;
var xRefForm = myDoc.crossReferenceFormats.item ('Page Number');
var tocEntriesPstyles = []
var CrossSource;
var CrossRefDest;

var tocEntries = app.selection[0].paragraphs;

for (var l = 0; l < tocEntries.length; l++) {
var eachentry = String(tocEntries[l].contents)
eachentry = eachentry.replace(/\t000\r/g, "")

CrossSource = myDoc.crossReferenceSources.add (tocEntries[l].paragraphs[0].insertionPoints[-2], xRefForm);

app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
app.findTextPreferences.appliedParagraphStyle = myDoc.paragraphStyles.item("ah")
app.findTextPreferences.findWhat = eachentry;
var myFoundItems = myDoc.findText();

if (myFoundItems.length > 0) {
CrossRefDest = myDoc.hyperlinkTextDestinations.add (myFoundItems[0], {name: myFoundItems[0].contents});
myDoc.hyperlinks.add (CrossSource, CrossRefDest);
}
}

 

Thanks,

Sathish

This topic has been closed for replies.
Correct answer m1b

Hi @SathishSekar_, I haven't tested your script, but somtimes it helps to reverse the direction of your loop, starting at the last and going backwards to the first. This will solve problems where a DOM reference becomes invalid by the actions inside the loop.

 

Please try replacing this line:

for (var l = 0; l < tocEntries.length; l++) {

with:

for (var l = tocEntries.length -1; l >= 0 ; l--) {

 

Let us know if it helps. If not, is it possible to share a small demo .indd file?

- Mark

1 reply

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
October 6, 2023

Hi @SathishSekar_, I haven't tested your script, but somtimes it helps to reverse the direction of your loop, starting at the last and going backwards to the first. This will solve problems where a DOM reference becomes invalid by the actions inside the loop.

 

Please try replacing this line:

for (var l = 0; l < tocEntries.length; l++) {

with:

for (var l = tocEntries.length -1; l >= 0 ; l--) {

 

Let us know if it helps. If not, is it possible to share a small demo .indd file?

- Mark

Known Participant
October 6, 2023

Hi @m1b,

 

Thanks for your valuable response. 

Yes after reversing the loop it works. However, it leaves atleast one entry behind without adding cross-reference(throws error so it has to skip that entry).

 

Thanks,

Sathish

FRIdNGE
October 6, 2023

\t000$\r?

 

(^/)  The Jedi