Chrome扩展,JQuery错误“;未捕获的类型错误:Object[Object Object]没有方法'te

Chrome Extension, JQuery error "Uncaught TypeError: Object [object Object] has no method 'text'"

本文关键字:Object 错误 有方法 te JQuery 扩展 Chrome 类型      更新时间:2023-09-26

我在上下文脚本中使用JQuery时遇到了一个令人困惑的问题。我正试图在facebook上运行一些JavaScript,但我一直收到这个错误";未捕获的类型错误:Object[Object Object]没有方法"text";。

在我的manifest.json中,我的上下文脚本是这样声明的:

"content_scripts": [
  {
    "matches": ["https://*.facebook.com/*"],
    "js": ["jquery.js", "misc.js", "facebook.js"],
    "all_frames": true,
    "run_at": "document_end"
  },
  //.... there are other pages that are get injected with contexts scrips here as well that aren't having this same issue.
]

我使用的是JQuery v1.7.1,misc.js有这样的功能:

function findString(search, element) {
    element = (typeof element === "undefined") ? "td" : element;
    var x = $(element).filter(function () {
        return new RegExp('^''s*' + search + '''s*$').test($(this).text());
    });
    return x;
}

根据我之前的一个问题,facebook.js有两次不同的编码尝试,第一次只是常规的JQuery:

var name = $("a._8_2"); //I did check, and on all my friend's profiles the class "_8_2" appears to be unique every time.
if (name.length){
  var nmTxt = name.text();
  name.text("chupacabra");  
}

这是一次试图在facebook个人资料页面上瞄准这个名字的尝试,该页面的结构如下:

<div class="_6-e">
  <h2 class="_6-f">
    <a class="_8_2" href="https://www.facebook.com/profileurlhere">FirstName LastName</a>
  </h2>
</div>

这不起作用,我得到了我提到的错误,并厌倦了用var name = $("div._6-3");找到它,得到了同样的结果。然后我尝试了一个我认为非常混乱的解决方法:

var name = findString(document.title, "a"); //this method is defined in misc.js, see link above
if (name.length){
  var nmTxt = name.text();
  name.text("chupacabra");
}

但这仍然没有奏效。我在var nmTxt = name.text();上遇到了同样的错误,我不知道为什么,尤其是因为我在其他页面上(在这个非常相同的扩展中)注入了与此非常相似的脚本,并且这些脚本正在按预期工作。

提前感谢大家!

name在您的全局范围内,因此它实际上与window.name冲突。window.name静默地将其值转换为字符串,这就是错误的来源:

> window.name = $('<a>')
> window.name
"[object Object]"
> window.fooname = $('<a>')
> window.fooname
[<a>​</a>​]

因此,要修复它,可以将代码封装在一个匿名函数中,以防止事情泄露到全局范围:

(function() {
  ...
})();

或者使用其他变量名。我会使用自动执行的匿名函数。