Skip to content

Instantly share code, notes, and snippets.

@mrrcollins
Created February 25, 2024 17:07
Show Gist options
  • Save mrrcollins/bdaae5900be3a369e11dc027eb2d57d7 to your computer and use it in GitHub Desktop.
Save mrrcollins/bdaae5900be3a369e11dc027eb2d57d7 to your computer and use it in GitHub Desktop.
YOURLS create short url
javascript:(function() {
var currentPage = encodeURIComponent(window.location.href);
var apiCall = 'https://SERVERADDRESS/yourls-api.php?signature=APIKEY&action=shorturl&url=' + currentPage;
fetch(apiCall)
.then(response => response.text())
.then(data => {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(data,"text/xml");
var title = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
var shorturl = xmlDoc.getElementsByTagName("shorturl")[0].childNodes[0].nodeValue;
//alert('Title: ' + title + '\nShort URL: ' + shorturl); // Keep the alert if you want
// Workaround for copying to clipboard
var textarea = document.createElement('textarea');
textarea.value = shorturl;
document.body.appendChild(textarea);
textarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textarea);
})
.catch(error => console.error('Error:', error));
})();
@mrrcollins
Copy link
Author

mrrcollins commented Feb 25, 2024

I wanted a way to create short URLs from a bookmarklet without dealing with logging in. This uses the signature API key to create short urls. The shorturls are copied to the clipboard.

To use:

  1. Set up a CORS header to allow access
  2. Replace SERVERADDRESS with your server name
  3. Replace APIKEY with your signature from the YOURLS admin page

The Javascript console under Web Developer tools is your friend when things don't seem to be happening.

I used Bookmarkleter to convert the javascript to a bookmarklet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment