1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| "use strict";
console.log("%cdébut script de contenu", "background: #8FF");
console.log("document.readyState = ", document.readyState);
// en cas de rechargement de lextension, empêche dagir après "document_end"
if ("loading" === document.readyState || "interactive" === document.readyState) {
const getAllNumMatches = (text) => {
const matches = [];
const phoneRegex = /0\d([\s.]?)\d{2}(?:\1\d{2}){3}/g;
let match = null;
while (match = phoneRegex.exec(text)) {
const length = match[0].length;
matches.push({
index : phoneRegex.lastIndex - length,
text : match[0],
length : length
});
}
return matches;
};
// peut-être plus économe en mémoire sur les grosses pages (à tester)
//const getAllNumMatches = function* (text) {
// const phoneRegex = /0\d([\s.]?)\d{2}(?:\1\d{2}){3}/g;
//
// let match = null;
// while (match = phoneRegex.exec(text)) {
// const length = match[0].length;
// yield {
// index : phoneRegex.lastIndex - length,
// text : match[0],
// length : length
// };
// }
//};
const transformNums = (element) => {
// on doit travailler sur une copie de element.childNodes pour le « geler »,
// sinon il se met à jour et inclut nos nuds nouvellement ajoutés
for (const node of Array.from(element.childNodes)) {
switch (node.nodeType) {
case Node.TEXT_NODE: {
const text = node.data.trim();
if (!text) {
console.log("%c(espaces blancs ignorés)", "color: gray");
}
else {
console.log("#text:", text);
for (const match of getAllNumMatches(text)) {
console.log(match);
const numTextNode = match.index > 0
? node.splitText(match.index + 1)
: node;
const restTextNode = match.length < node.data.length
? numTextNode.splitText(match.length)
: null;
const $a = document.createElement("a");
const canonicalNum = match.text.replace(/(?!^)\D+/g, "");
$a.href = `tel:${canonicalNum}`; // à remplacer par ce quon veut
$a.textContent = canonicalNum;
// ici éventuellement rajouter un gestionnaire de "click" sur $a
numTextNode.replaceWith($a);
}
}
break;
}
case Node.ELEMENT_NODE: {
// appel récursif
transformNums(node);
break;
}
default: {
// ignore tous les autres types de nuds
break;
}
}
}
};
//console.log(document.body.innerHTML);
//document.body.insertAdjacentHTML("afterbegin",
// '<p style="color: red">Contenu injecté par lextension</p>');
//browser.storage.local.set({ reponse: 42 })
// .then(() => { console.log("storage set a réussi"); })
// .catch((reason) => { console.error(reason); });
browser.storage.local.get()
.then((data) => console.log("storage get :", data));
transformNums(document.body);
}
console.log("%cfin script de contenu", "background: #8FF"); |
Partager