繁体   English   中英

Chrome扩展程序可更改页面中的字词

[英]Chrome Extension to change words in page

我正在编写一个Chrome扩展程序,可将网页中的某些字词更改为其他字词。 这就是我所拥有的,我没有任何改变的话,也没有控制台错误。

myscript.js

var text = $(this).text();
var mapObj = {
   is:"tests",
   a:"AAAAAAAA",
   the:"testing"
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
$(this).text(text.replace(re, function(matched){
    return mapObj[matched.toLowerCase()];
}));

的manifest.json

{
  "manifest_version": 2,

  "name": "example",
  "description": "bla",
  "version": "1.0",

 /* "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },*/
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js":["js/jquery-3.1.1.js", "myscript.js"],
      "run_at": "document_end"

    }
  ],
  "permissions": [
    "activeTab",
    "<all_urls>"
  ]
}

我跟着这个家伙的回答,但这并没有改变我的话。 我究竟做错了什么?

更新我试过这个:

$(this).text(text.replace(new RegExp("the", "g"), "test"));

它的工作原理。 和这个:

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("the", "g"), "hunter");

它的工作原理。 所以它显然与此有关(而不是任何其他文件或权限。正确吗?):

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
$(this).text(text.replace(re, function(matched){
    return mapObj[matched.toLowerCase()];
}));

最后,我想循环遍历每个单词并测试是否需要更改,如果是,请更改它。 如果有更好的方法,请告诉我。

通过这样做找到答案:

var html = document.querySelector('html');
var walker = document.createTreeWalker(html, NodeFilter.SHOW_TEXT);
var node;


    var oneArray= ["the"];
    var twoArray= ["bob"];
    var one;
    var two;


while (node = walker.nextNode()) {
    for (i=0; i<engWords.length;i++) {

        one= new RegExp(oneArray[i],"g");
        two= twoArray[i];

        node.nodeValue = node.nodeValue.replace(one, two);

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM