Skip to content

Instantly share code, notes, and snippets.

@vctls
Created June 25, 2021 10:05
Show Gist options
  • Save vctls/92d7985d455867f711c296d8969928ef to your computer and use it in GitHub Desktop.
Save vctls/92d7985d455867f711c296d8969928ef to your computer and use it in GitHub Desktop.
User script that warns if the text of a clicked link looks like a domain that does not match the href attribute.
// ==UserScript==
// @name URL Scam Detection
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Warns if the text of a clicked link looks like a domain that does not match the href attribute.
// @author vctls
// @match *
// @grant none
// ==/UserScript==
function warnIfLinkNotMatching(e){
const el = e.target;
if (!el.nodeName === 'A') {
return;
}
const href = el.href;
const text = el.text;
// This should match most domain names, and probably give some false positives too.
const regex = /(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9-]{1,30}\.[a-z]{2,})/;
// TODO We're only looking for something that looks like a domain name, not a full URL.
// This will obviously break window.open() if the full text doesn't correspond exactly to a URL.
// Use a different regex to get the full link instead.
const textMatches = text.match(regex);
const hrefMatches = href.match(regex);
if (
textMatches !== null
&& textMatches[0] !== hrefMatches[0]
){
e.preventDefault();
const selection = prompt(
"The link you clicked looks like a domain name, but doesn't match the underlying URL. "
+ "Which domain would you like to follow?"
+ `\nA: ${textMatches[0]}\nB: ${hrefMatches[0]}`
);
if (selection === 'B') {
window.open(href, '_blank').focus();
}
if (selection === 'A') {
window.open(text, '_blank').focus();
}
}
}
(function() {
'use strict';
document.addEventListener('click', warnIfLinkNotMatching);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment