Skip to content

Instantly share code, notes, and snippets.

@mvark
Created May 6, 2021 10:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvark/65bf25dffc64d3c2ad28a6f4866d3caa to your computer and use it in GitHub Desktop.
Save mvark/65bf25dffc64d3c2ad28a6f4866d3caa to your computer and use it in GitHub Desktop.
Bookmarklet that calls a REST API to fetch geolocation details for a given IP address
//IP LOCATION TRACKER BOOKMARKLET
//Original source: https://funbutlearn.com/2016/06/ip-location-tracker-bookmarklet-created.html
//modified API service from http://ip-api.com which doesn't support HTTPS to https://ipapi.co/ to have a secure endpoint & avoid Mixed Content blocking issue
javascript: (function() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var ipPattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
var res = ipPattern.test(text);
if (res) {
showIP(text);
} else {
var ip = prompt("Please provide an IP address");
showIP(ip);
}
function showIP(ipAddr) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ipDetails = JSON.parse(xhttp.responseText);
var ipAddr = "";
for (key in ipDetails) {
ipAddr += key.toUpperCase() + " : " + ipDetails[key] + "\n";
}
alert(ipAddr);
}
};
xhttp.open("GET", "https://ipapi.co/" + ipAddr + "/json/", true);
xhttp.send();
}
})()
javascript:(function(){var e="";if(window.getSelection){e=window.getSelection().toString()}else{if(document.selection&&document.selection.type!="Control"){e=document.selection.createRange().text}}var a=new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");var b=a.test(e);if(b){c(e)}else{var d=prompt("Please provide an IP address");c(d)}function c(f){var g=new XMLHttpRequest();g.onreadystatechange=function(){if(g.readyState==4&&g.status==200){var i=JSON.parse(g.responseText);var h="";for(key in i){h+=key.toUpperCase()+" : "+i[key]+"\n"}alert(h)}};g.open("GET","https://ipapi.co/"+f+"/json/",true);g.send()}})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment