Trying to make a hyperlinking script
Hi,
I'm trying to make a script where it will take highlighted text, make it into a hyperlink, format it with a character style and make the destination a page within the document, specifically the number that is the highlighted text. The usecase is an index - so I highlight 151, for example, and the script applies the character style "Hyperlink" and makes the text a hyperlink to page 151. Below is what I have so far but I'm tweaking a script I found elsewhere (source below) and I'm really struggling. I'm afraid this is not a particular strength of mine.
If anyone fancies digging into it and seeing if they can make it work, I'd be very grateful!
Thanks, Eubhal
Script:
Main();
// If you want the script to be un-doable, comment out the line above, and remove the comment from the line below
// app.doScript(Main, undefined, undefined, UndoModes.ENTIRE_SCRIPT,”Run Script”);
function Main() {
//This takes the text that you have highlighted on the page
var myHighlightedText = app.selection[0].contents;
//this checks that you have selected some text (with a length greater than 1). If not it will tell you to select some text.
if(myHighlightedText.length < 1){
alert("No text has been selected");
}
//This targets the text frame which the highlighted text is within
var myTextFrame = app.selection[0].parentTextFrames[0];
//The highlighted text in Indesign is just a plain string – which is not an object in InDesign and therefore cannot be formatted via InDesign styles.
//This gets the index number from the start of the selected text
var styleStartIndex = app.selection[0].index;
//This gets the index number from the end of the highlighted text
var styleEndIndex = styleStartIndex + myHighlightedText.length-1;
//select the text by their index numbers previously defined.
var mySelection = myTextFrame.characters.itemByRange(styleStartIndex, styleEndIndex);
//apply the character style to it.
mySelection.appliedCharacterStyle="Hyperlink";
// To take the selected text and add a hyperlink to it, first define both the destination and the source.
//The below defines the source of the hyperlink to be the highlighted text “mySelection”
var source = app.documents[0].hyperlinkTextSources.add(mySelection);
//Destination”s” plural is used because we are selecting (via its name) a single hyperlink destination from the ARRAY of possible destinations.
var dest = app.documents[0].hyperlinkTextDestinations.itemByName("Destination 3");
//this applies the hyperlink referencing the source and the destination
app.documents[0].hyperlinks.add(source,dest, {name:myHighlightedText});
//the {name:myHighlightedText} section is naming the new hyperlink with the text that has been selected.
}
Original source: https://creativepro.com/topic/indesign-scripting-hyperlinks/
