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