【发布时间】:2016-10-03 20:19:34
【问题描述】:
这是我得到的控制台错误,它阻止我访问 DOM。我可以验证 id 是否存在,但不确定这是否是某种安全功能:\
【问题讨论】:
标签: javascript google-chrome console google-chrome-devtools
这是我得到的控制台错误,它阻止我访问 DOM。我可以验证 id 是否存在,但不确定这是否是某种安全功能:\
【问题讨论】:
标签: javascript google-chrome console google-chrome-devtools
与此错误相关的 Facebook 实际上并未使用 jQuery 库。如果您在控制台中运行jQuery,您将收到错误消息。 $ 快捷方式实际上是另一个库的选择器。这就是您收到错误的原因。
您可以使用内容脚本通过script 标签将 jQuery 库注入网页:
var s = document.createElement('script');
s.src = chrome.extension.getURL('path_to_jquery/jQuery.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head || document.documentElement).appendChild(s);
然后您将能够在页面本身上使用 jQuery,使用 jQuery('#id')。你可以为它定义一个新的快捷方式:
var jq = jQuery.noConflict();
jq('#id'); // using the new shortcut
您还可以使用 jQuery 访问 DOM,方法是将 jQuery 作为内容脚本以及您的其他脚本。以下内容进入manifest.json:
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery-1.12.4.min.js", "your_script.js"]
在your_script.js 中,您应该可以正常使用jQuery,因为上下文与实际页面不同,因此与$ 变量没有冲突。您可以通过将top 更改为扩展本身来将console 上下文设置为扩展。
【讨论】:
jQuery()。如果您想将其永久保存在页面中,请使用我展示的第一种方法,您可以使用 CDN 或将其打包在扩展程序本身中。
getElementsByClassName() 返回元素的集合,因此您必须循环修改每个元素的样式。要访问第一个,请在索引 0 处访问它。