2

我在上下文脚本中使用 JQuery 时遇到了一个令人费解的问题。我正在尝试在 facebook 上运行一些 JavaScript,并且不断收到此错误“未捕获的类型错误:对象 [对象对象] 没有方法‘文本’”。

在我的 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();,我不知道为什么,特别是因为我在其他页面上注入了与此非常相似的脚本(在这个非常相同的扩展名中),并且这些脚本正在按预期工作。

提前谢谢大家!

4

1 回答 1

4

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

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

所以要修复它,要么将你的代码包装在一个匿名函数中,以防止事情泄漏到全局范围内:

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

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

于 2013-07-15T23:39:53.887 回答