Skip to content

Instantly share code, notes, and snippets.

@Emmunaf
Last active April 13, 2022 07:52
Show Gist options
  • Save Emmunaf/8ebd24b17503668d71ccea8d30bdbbf7 to your computer and use it in GitHub Desktop.
Save Emmunaf/8ebd24b17503668d71ccea8d30bdbbf7 to your computer and use it in GitHub Desktop.
Extract wa.me from autodetected cellphone starting with 3xx. Also working with 3xx-yyyyyyy or 3xx yyyyyyy
// ==UserScript==
// @name Phone Number Id
// @author emmunaf ([email protected])
// @version 1
// @grant none
// ==/UserScript==
(function () {
const trackRegexUS = /((\d{3})\s?\-?\s?(\d{4}))|(\(\d{3}\)\s?\d{3}\s?\-\s?\d{4})|(\d{3}\s\d{4})/g;
const trackRegex = /(3(\d{2})\s?\-?\s?(\d{7}))/g;
// tags we will scan looking for un-hyperlinked urls
var allowedParents = [
"abbr", "acronym", "address", "applet", "b", "bdo", "big", "blockquote", "body",
"caption", "center", "cite", "code", "dd", "del", "div", "dfn", "dt", "em",
"fieldset", "font", "form", "h1", "h2", "h3", "h4", "h5", "h6", "i", "iframe",
"ins", "kdb", "li", "nobr", "object", "pre", "p", "q", "samp", "small", "span", "strike",
"s", "strong", "sub", "sup", "td", "th", "tt", "u", "var"
];
var xpath = "//text()[(parent::" + allowedParents.join(" or parent::") + ")" + "]";
var candidates = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var cand = null, i = 0; (cand = candidates.snapshotItem(i)); i++) {
if (trackRegex.test(cand.nodeValue)) {
var span = document.createElement("span");
var source = cand.nodeValue;
cand.parentNode.replaceChild(span, cand);
trackRegex.lastIndex = 0;
for (var match = null, lastLastIndex = 0; (match = trackRegex.exec(source)); ) {
span.appendChild(document.createTextNode(source.substring(lastLastIndex, match.index)));
var a = document.createElement("i");
var b = document.createElement("b");
var c = document.createElement('a');
var cleanPhone = match[0].replace(/ /g,"");
var linkText = document.createTextNode(cleanPhone);
c.appendChild(linkText);
c.title = cleanPhone;
c.target = "_blank";
c.href = "https://wa.me/39"+cleanPhone+"?text=Buongiorno";
b.appendChild(document.createTextNode(match[0]));
a.appendChild(b);
span.appendChild(a);
span.appendChild(c);
lastLastIndex = trackRegex.lastIndex;
}
span.appendChild(document.createTextNode(source.substring(lastLastIndex)));
span.normalize();
}
}
})();
/*
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment