Action

URL to Markdown Link

Posted by @macdhuibh, Last update over 4 years ago

This action makes link in Markdown from a selected URL.

The link’s text is the Title of the page fetched from the URL.

For example:

http://dobyfriday.com

Becomes:

[Do By Friday](http://dobyfriday.com)

Steps

  • script

    function promptForTitle() {
    	let prompt = Prompt.create();
    	prompt.title = "URL to Markdown Link";
    	prompt.message = "Please add a title, we couldn't fetch the link's title from the internet";
    	prompt.addTextField("title", "Title", "");
    	prompt.addButton("Create link");
    	
    	let didSelect = prompt.show();
    	
    	let title = prompt.fieldValues["title"];
    	
    	if (prompt.buttonPressed == "Create link") {
    		createMarkdownLink(title, url)
    	}
    
    };
    
    function promptForURL() {
    	let prompt = Prompt.create();
    	prompt.title = "URL to Markdown Link";
    	prompt.message = "Please provide a URL, so that we can try fetching the title from the internet";
    	prompt.addTextField("url", "URL", "");
    	prompt.addButton("Next");
    	
    	let didSelect = prompt.show();
    	
     	return prompt.fieldValues["url"];
    };
    
    
    function createMarkdownLink(title, url) {
    		markdown_link = `[${title}](${url})`
      		editor.setSelectedText(markdown_link)
    };
    
    
    let url = editor.getSelectedText() // Get selected URL
    
    if (url == "") {
    	url = promptForURL();
    }
    
    var http = HTTP.create(); // create HTTP object
    
    var response = http.request({
    									"url": url,
    									"method": "GET",
    									}); // GET the HTML of the page
    
    if (response.success) {
    	var text = response.responseText;
    	
    	// Grab the Title of the page
    	let re = new RegExp('<title>(.*?)<\/title>');
    
    	var title = re.exec(text);
    	editor.setSelectedText(title)
    	if (title) {
    		title = title[1];
      		title = HTML.unescape(title);
    		
    		createMarkdownLink(title, url);
    	}
    	else {
    		promptForTitle()
    	};
    }
    else if (response.error) {
    	promptForTitle();
    };
    

Options

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