无法使用注入 jQuery
Can't use injected jQuery
我想在 Chrome 扩展中将 jQuery 注入网页(带有内容脚本)。
我试过了,但有些事情让我很困惑。
这是我的 manifest.json
:
{
"name": "test",
"description": "test content script.",
"version": "0.0.1",
"background": {
"scripts": ["jquery-1.10.2.js", "popup.js"]
},
"permissions": ["tabs", "notifications", "http://*/*", "https://*/*"],
"browser_action": {
"default_title": "test",
"default_icon": "icon.png"
},
"options_page": "manage.html",
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["jquery-1.10.2.js"]
}
],
"manifest_version": 2
}
jquery-1.10.2.js:
/*jquery's orign code*/
console.log("end of jquery");
我可以看到控制台消息,但我仍然无法使用 jQuery。
我写了一个简单的网站并尝试通过内容脚本包含 jQuery 而不是使用 <script>
标签添加它。
在 Dev Tool 控制台中,我输入 window.jQuery
或 $("li").siblings()
。
如果在页面中包含 jQuery,它会起作用,但如果它注入了内容脚本,它会显示 jQuery
为未定义。
为什么会这样?
我用过这个,效果很好。也许你的 jquery 路径不正确。
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["js/jquery.min.js", "js/socket/socket.io.js","js/socket/client.js"],
"run_at": "document_idle"
}]
情况与非常相似。
内容脚本直播in their own, isolated JavaScript context。这样做是为了让扩展添加的脚本不会与页面或彼此冲突。
当您打开 Dev Tools 控制台时,它会显示来自网页所有上下文的控制台消息:页面上下文、iframe 上下文(也是独立的)和内容脚本上下文。这就是您看到日志消息的原因。
然而,虽然它可以一次显示所有消息,但如果您尝试执行某项操作,它必须转到一个上下文。默认情况下,它是页面的上下文:<top frame>
就在控制台上方。
要在扩展的上下文中执行某些操作,您需要切换到它:
如果您想让某些 JavaScript 可用于页面上下文,则需要将其作为 <script>
标记注入页面本身。参见 this question。
我想在 Chrome 扩展中将 jQuery 注入网页(带有内容脚本)。
我试过了,但有些事情让我很困惑。
这是我的 manifest.json
:
{
"name": "test",
"description": "test content script.",
"version": "0.0.1",
"background": {
"scripts": ["jquery-1.10.2.js", "popup.js"]
},
"permissions": ["tabs", "notifications", "http://*/*", "https://*/*"],
"browser_action": {
"default_title": "test",
"default_icon": "icon.png"
},
"options_page": "manage.html",
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["jquery-1.10.2.js"]
}
],
"manifest_version": 2
}
jquery-1.10.2.js:
/*jquery's orign code*/
console.log("end of jquery");
我可以看到控制台消息,但我仍然无法使用 jQuery。
我写了一个简单的网站并尝试通过内容脚本包含 jQuery 而不是使用 <script>
标签添加它。
在 Dev Tool 控制台中,我输入 window.jQuery
或 $("li").siblings()
。
如果在页面中包含 jQuery,它会起作用,但如果它注入了内容脚本,它会显示 jQuery
为未定义。
为什么会这样?
我用过这个,效果很好。也许你的 jquery 路径不正确。
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["js/jquery.min.js", "js/socket/socket.io.js","js/socket/client.js"],
"run_at": "document_idle"
}]
情况与
内容脚本直播in their own, isolated JavaScript context。这样做是为了让扩展添加的脚本不会与页面或彼此冲突。
当您打开 Dev Tools 控制台时,它会显示来自网页所有上下文的控制台消息:页面上下文、iframe 上下文(也是独立的)和内容脚本上下文。这就是您看到日志消息的原因。
然而,虽然它可以一次显示所有消息,但如果您尝试执行某项操作,它必须转到一个上下文。默认情况下,它是页面的上下文:<top frame>
就在控制台上方。
要在扩展的上下文中执行某些操作,您需要切换到它:
如果您想让某些 JavaScript 可用于页面上下文,则需要将其作为 <script>
标记注入页面本身。参见 this question。