I'd like to use Tampermonkey to strip the <a href="tel:
from telephone numbers on a webpage on our intranet.
I've installed Tampermonkey and bodged the following script
// ==UserScript==
// @name Localhost Tel: link remover
// @author Dan
// @match *://localhost/*
// @version 2019.08.15
// @grant none
// @run-at document-start
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
console.log('Started Localhost Tel: killer...');
// ==/UserScript==
var anchors = document.getElementsByTagName('tel');
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = anchors[i].href.split("?")[0];
}
but I'm way out of my depth! I've tried Googling for "delinkify" and "strip links" but even if I could find someone suitable, I'm specifically looking to strip tel: links not just all links.
Thanks!
EDIT:
// ==UserScript==
// @name tel: remover
// @match *redacted*
// @version 2019.08.15
// @run-at document-end
// ==/UserScript==
const linksTel = [...document.querySelectorAll("a")].filter((link)=>link.href.startsWith("tel:"));
for(let linkTel of linksTel) {
const parent = linkTel.parentNode;
// Trim will remove extra spaces at the beginning and end
const newTextNode = new Text(linkTel.innerText.trim());
parent.replaceChild(newTextNode, linkTel);
}
alert("check");
The tag name you're looking for is a
as in <a ... >
. So use:
const links = document.querySelectorAll("a");
But that gives you ALL the links. So you will need to only filter for those that have tel:
in the beginning. There's an utility method .filter
, but it is only available for arrays, not HTMLElementCollection
that is returned by document queries. You can unroll the collection in array like this:
const linksArray = [...links];
Now the filter:
const linksTel = linksArray.filter((link)=>link.href.startsWith("tel:"));
Now you have all the links that start with tel
. To replace with just plain text node, you could do:
for(let linkTel of linksTel) {
const parent = linkTel.parentNode;
// Trim will remove extra spaces at the beginning and end
const newTextNode = new Text(linkTel.innerText.trim());
parent.replaceChild(newTextNode, linkTel);
}
That should be it.
Also mind this! You use @run-at document-start . That's not what you want. You need to use @run-at document-end
. At document-start
, the HTML was not loaded yet, so you cannot manipulate it.
See it all together below:
const linksTel = [...document.querySelectorAll("a")].filter((link)=>link.href.startsWith("tel:")); for(let linkTel of linksTel) { const parent = linkTel.parentNode; // Trim will remove extra spaces at the beginning and end const newTextNode = new Text(linkTel.innerText.trim()); parent.replaceChild(newTextNode, linkTel); }
<a href="tel:123456489">123456489</a><br /> <a href="/test">Tet page</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.