我正在编写测试Chrome扩展程序,我尝试在当前页面上突出显示所有关键字。不幸的是,我认为我的逻辑中存在一个小差距,因为它遇到了无限循环。具体来说,在找到第一个关键字匹配后(假设正则表达式匹配单词'突出显示'),它会插入节点,然后拉出并插入相同的突出显示' textnode一遍又一遍。相关代码如下:
// Get all elements on the page
const elements = document.getElementsByTagName('*');
for (let i = 0; i < elements.length; i++) {
for (let j = 0; j < elements[i].childNodes.length; j++) {
// Loop through each node
let currNode = elements[i].childNodes[j];
// Check for textnode
if (currNode.nodeType === 3) {
// Get first/next match
for (let match; match = regex.exec(currNode.nodeValue); ) {
// Create highlighted element
let hlElement = document.createElement('span');
hlElement.appendChild(document.createTextNode(match[0]));
hlElement.className = 'highlight';
// Split current textnode at match and insert higlighted match in between
let nextNode = currNode.splitText(match.index);
nextNode.nodeValue = nextNode.nodeValue.substring(match[0].length);
currNode.parentNode.insertBefore(hlElement, nextNode);
currNode = nextNode;
}
}
}
}