Reply To: Export URL hyperlinks

#1237873
Kal Starkis
Member

Hi Khaled. It’s been a good while since I threw that script together, but looking back at it now, I can see that it only works if all the hyperlinks in the document have URL Destinations. If you have other types of destinations (like Text Destinations for example), the script will fail at the line that tries to get the destinationURL. So let’s fix it…

I think the easiest way is to just catch the error when it happens. Since we’re only interested in finding actual URLs, anything that isn’t a URL can safely be ignored. So, here’s an updated version of the script that does just that…

// Get all our document hyperlinks
var myDocument = app.documents[0];
var myDocumentHyperlinks = myDocument.hyperlinks.everyItem().getElements();
// Create an empty object to store all the URLs (along with linked text)
var indexOfURLs = {};
// Iterate over all the document hyperlinks and add each one to the object
for (var i = 0; i < myDocumentHyperlinks.length; i++) {
    var hyperlink = myDocumentHyperlinks[i];
    // Get linked text (title) and URL
    var title = hyperlink.source.sourceText.contents;
    var url;
    try {
        url = hyperlink.destination.destinationURL;
    } catch (err) {
        // The destination is not a URL. Ignore it.
        continue;
    }
    // Add title and URL to the list
    indexOfURLs[title] = url;
}
// Print out all the URLs
for (var key in indexOfURLs) {
  $.writeln(key + ": " + indexOfURLs[key]);
}

Please let us know how you go. :-) (I find that it’s not uncommon to give up precious time on forums like this one to try and help others only to never hear back from people, as was the case with the OP on this thread. We’re all human and a little ‘thanks for your help’ goes a long way to keeping any community alive and helpful.)

This article was last modified on April 12, 2020

Comments (0)

Loading comments...