Action

Open All URLs

Posted by RoyRogers, Last update about 4 years ago

Shows a list of all URLs in current draft to open in Safari
- Opens directly if only one link
- On Mac, choice to open all at once.

Steps

  • script

    // Open URLs in Draft
    // RV 2020-04-07 at 10:19
    
    // Opens all URL md-links in a draft
    
    // Alt. 1: If you have Markdown links:
    let re = /\[(.*?)\]\((.+?)\)/g;
    let pos = 2;
    
    // // Alt. 2: Plain URLs, simplified pattern, `http(s)//` required!:
    // let re = /(https?:\/\/)([a-z0-9]{3,40}\.)+[a-z]{2,6}[^ \t\n\(\)'";:]*/gi;
    // let pos = 1;
    
    (() => {
      
      let text = draft.content;
      let links = [...text.matchAll(re)]; // convert to array
      
      if (links.length == 0) {
        app.displayInfoMessage('No markdown links found!');
        return;
      } else if (links.length == 1) {
        openURL(links[0][pos]);
      } else {
        selectURLs(links);
      }
    })()
    
    function selectURLs(links) {
      let p = Prompt.create();
      p.title = 'URLs in current draft';
      p.message = 'Select URL to open:';
      
      if (device.systemName == 'macOS') {
        // Open all URL's (on Mac only)
        p.addButton('Open All URLs', -1);
      }
      
      let i = 0;
      for (let link of links) {
        let title = link[1];
        if (title == '') {
          title = link[pos];
        }
        p.addButton(title, i);
        i++;
      }
      
      if (!p.show()) {
        context.cancel('canceled by user');
        return;
      }
      
      i = parseInt(p.buttonPressed);
      if (i == -1) {
        for (const link of links) {
          // Open all URL's (on Mac only)
          openURL(link[pos]);
        }
      } else {
        openURL(links[i][pos]);
      }
    }
    
    function openURL(url) {
    	if (!url.match(/:\/\//)) {
    	  url = 'http://' + url;
    	}
      // try {
      //   let result = app.openURL(url, false);
      // } catch(err) {
      //   app.displayErrorMessage(err.message + ': ' + url);
      // }
      
      let result = app.openURL(url, false)
      if (result) {
      		return true;
      } else {
        app.displayErrorMessage('Invalid: ' + url);
        return false;
      }
    }
    
    
    

Options

  • After Success Default
    Notification Error
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.