未在Chrome扩展内容脚本中定义$ x()函数 [英] $x() function is not defined inside a Chrome extension, content script
问题描述
$ X(//一个[含有(@href,) JPG。]);
按照预期从开发人员工具命令提示符运行。但是,当在扩展的内容脚本中,我得到了一个' $ x未定义
'。
为什么是这在内容脚本中不可用,或者在content-script / Chrome扩展中有特殊的访问方式吗?
我在Debian上使用Chrome 22。
$ x()
不是运行时的一部分网页或内容脚本的环境。它是 Chrome开发工具的命令行API的一部分。
要在内容脚本中使用XPath,您需要按照正常的方式进行操作,DevTools方便的快捷方式不可用。
您的代码如下所示:
var jpgLinks = document.evaluate(
//a[contains(@href,'.jpg')],
文档,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
var numLinks = jpgLinks.snapshotLength; (var J = 0; J var thisLink = jpgLinks.snapshotItem(J);
。
console.log(Link,J,=,thisLink);
- 这就是 $ x()
为你在幕后工作。
当你在,请考虑切换到 CSS选择器。然后相同的功能是:
$ $ p $ code var jpgLinks = document.querySelectorAll(a [href $ ='。jpg']) ;
var numLinks = jpgLinks.length;
for(var J = 0; J
console.log(Link,J,=,thisLink);
}
- 这在我的书中更加美味。
$x("//a[contains(@href,'.jpg')]");
works as expected from the developer tools command prompt. But, when in an extension's content-script I get a '$x is not defined
'.
Why is this not available in a content-script or is there a special way of accessing it inside a content-script / Chrome extension?
I'm using Chrome 22 on Debian.
$x()
is not part of the run-time environment of a web page or content script. It is a tool that is part of the Command Line API for Chrome's DevTools.
To use XPath in a content script, you need to do it the normal way, the DevTools convenient shortcut is not available.
Your code would look like this:
var jpgLinks = document.evaluate (
"//a[contains(@href,'.jpg')]",
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
var numLinks = jpgLinks.snapshotLength;
for (var J = 0; J < numLinks; ++J) {
var thisLink = jpgLinks.snapshotItem (J);
console.log ("Link ", J, " = ", thisLink);
}
-- which is the kind of thing that $x()
was doing for you, behind the scenes.
While you are at it, consider switching to CSS selectors. Then the same functionality is:
var jpgLinks = document.querySelectorAll ("a[href$='.jpg']");
var numLinks = jpgLinks.length;
for (var J = 0; J < numLinks; ++J) {
var thisLink = jpgLinks[J];
console.log ("Link ", J, " = ", thisLink);
}
-- which is much more palatable in my book.
这篇关于未在Chrome扩展内容脚本中定义$ x()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!