Action

Open A URL

Posted by drdrang, Last update 3 months ago - Unlisted

Shows a list of all URLs in current draft to open in Safari
Opens directly if only one link.

Steps

  • script

    // Open URLs in Draft
    // RoyRogers: https://forums.getdrafts.com/t/open-markdon-urls/7092
    // Markdown reference links: drdrang
    
    // Opens all URL md-links in a draft
    
    // Alt. 1: If you have Markdown links:
    let inlineRE = /\[(.*?)\]\((.+?)\)/g;
    let refRE = /^\[([^\^].*)\]:\s*(\S+)/gm;
    let ref = 1
    let url = 2;
    
    (() => {
      
      let text = draft.content;
      let inlineLinks = [...text.matchAll(inlineRE)];
      let refLinks = [...text.matchAll(refRE)];
      let links = inlineLinks.concat(refLinks);
      
      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:';
     
     let i = 0;
      for (let link of links) {
        let title = link[ref];
        if (title == '') {
          title = link[url];
        }
        p.addButton(title, i);
        i++;
      }
      
      if (!p.show()) {
        context.cancel('canceled by user');
        return;
      }
      
      i = parseInt(p.buttonPressed);
      openURL(links[i][url]);
    }
    
    function openURL(url) {
    	if (!url.match(/:\/\//)) {
    	  url = 'http://' + 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.