Script to Open All URLs

This script is a companion to my Insert All Open Safari Tabs script.

When you run it, it will look at the current item and all of its children, pull out any items that are URL’s and open them as tabs of a single, new Safari window.

I use this with the script I linked above: when I want to take a break from something I’m researching, I dump all the open tabs into TaskPaper as children of a new item (e.g. “Loan Options”). Then I close Safari.

When I want to pick up my project again, I put the TaskPaper cursor on the “Loan Options” item and run this script.

Here’s the source code:

function loadAllURLs(editor, options) {
  'use strict';

  function isURL(item) {  
    const text = item.trim()
    return text.match("https?://") && !text.includes(" ")
  }

  const selectedItem = editor.selection.endItem;
  const candidateItems = selectedItem.descendants.concat([selectedItem]);

  return candidateItems.map(item => item.bodyString).filter(isURL);
}

function openInNewWindow(urls) {
  const safari = Application("Safari");

  // open first link as a new tab in a new window
  safari.documents.push(safari.Document({url: urls[0]}));

  // now open the rest of the links as new tabs of that window
  for( let url of urls.slice(1) ) {
    const tab = safari.Tab({url: url});
    safari.windows[0].tabs.push(tab);
  }
}

const urls = Application("TaskPaper").documents[0].evaluate({
  script: loadAllURLs.toString()
});

if( urls.length > 0 ) {
  openInNewWindow(urls);
}

Update 4/7/21: Fix bug that opened an empty tab in the new window.

2 Likes

Added to Wiki