替换文本,但在谷歌chrome扩展内容脚本中保留链接

Replace text but keep links in google chrome extension content scripts

本文关键字:脚本 链接 保留 扩展 chrome 文本 谷歌 替换      更新时间:2023-09-26

我试图替换谷歌chrome上的单词,但遇到了一个问题。我能够成功地替换特定的单词,但它会杀死相关的html链接。

如何保持链接的有效性并替换文本?

这是我的chrome扩展内容脚本中的代码:

wordDict = {"the":"piano","and":"Hello", "a":"huh?"};
for (word in wordDict) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp('''b' + word + '''b',"gi"), wordDict[word]
    );
};

我不是regex表达式的专家,所以这是一个在页面上找到一个包含一个单词的超链接并用另一个单词替换它的解决方案。

for(var i = 0, l=document.links.length; i<l; i++) {
  if(document.links[i].innerText == "Word"){
    document.links[i].innerText = "Other Word";
  }
}

有了这个,您可以避免regex,但您仍然需要循环您的words对象。

另一方面,由于您说已经加载了jQuery,所以这个jQuery解决方案实现了您想要的功能,它在所有a标签中查找单词并替换它们。

jQuery.each( wordDict , function( key, value ) {
  jQuery( "a" ).each(function(){
    if(jQuery(this).text().match(key)) jQuery(this).text(value);
  });
});

第一个jQuery每个都循环字符串对象,第二个每个都循环页面上的所有a标记,如果匹配,它会根据对象上的值更改元素文本。

好的!两周后,我终于解决了这个问题。被忽略的是DOM中的子节点。我在下面使用的代码有效地处理了子节点,并保持了脚本的原始外观!

function replaceText(jsonArr) {
$("body *").textFinder(function() {
    for (var key in jsonArr) {
        var matcher = new RegExp('''b' + key + '''b', "gi");
        this.data = this.data.replace(matcher, jsonArr[key]);
    }
});
}
// jQuery plugin to find and replace text
jQuery.fn.textFinder = function( fn ) {
this.contents().each( scan );
// callback function to scan through the child nodes recursively
function scan() {
    var node = this.nodeName.toLowerCase();
    if( node === '#text' ) {
        fn.call( this );
    } else if( this.nodeType === 1 && this.childNodes && this.childNodes[0] && node !== 'script' && node !== 'textarea' ) {
        $(this).contents().each( scan );
    }
}
return this;
};