【发布时间】:2017-12-10 20:07:08
【问题描述】:
我正在尝试编写一个简单的 Chrome 扩展程序来从网站上获取有关公寓的信息,但我什至无法从 JQuery 中获取打开/单击功能。
manifest.json
{
"manifest_version": 2,
"name": "Flat",
"description": "Adds flats to app",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
],
"content_scripts": [
{
"matches": [
"https://www.spareroom.co.uk/flatshare/flatshare_detail.pl*",
],
"js": ["lib/jquery.min.js", "lib/bootstrap.min.js", "content.js"]
}
]
}
content.js
$(document).ready(function () {
console.log('Viewing flat');
$("#hello").on("click", function () {
console.log("Hello");
});
$("#hello").click(function () {
console.log("hello");
});
});
popup.html
<html>
<head>
<title>Popup</title>
<link rel="stylesheet" href="lib/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="lib/jquery.min.js"></script>
<script src="lib/bootstrap.min.js"></script>
<script src="content.js"></script>
</head>
<body>
<div class="container">
<button id="hello" class="btn btn-default">Add Flat</button>
</div>
</body>
</html>
我不确定这里的问题是什么。 JQuery 是 3.2.1,Bootstrap 是 3.3.7。这里没有很多与 JQuery 相关的 Chrome 扩展问题。我找到了这个Chrome extensions with jQuery,但我已经有了封装其他代码的文档就绪函数。还查看了这个$(document).click() not working in chrome extension,但该解决方案没有利用 JQuery 的点击/打开功能。
【问题讨论】:
-
该站点可能会在触发文档就绪事件后动态添加其内容。您可以通过在内容脚本中添加 console.log($("#hello")[0]) 来验证这一点。如果它为空/未定义,则需要通过 setTimeout/setInterval 或 window.onload 或 MutationObserver 等待。
-
这确实返回 undefined 这对我来说没有意义。我的假设是 $(document) 指的是 popup.html 而不是实际的网页。但这似乎不正确。我不明白什么?
-
请务必阅读extension architecture overview。内容脚本和弹出窗口都不能直接相互引用,它们运行在浏览器的不同部分。
-
好吧,我想我得重读一遍,但看起来我得把一些东西移到背景页面。
-
我看到您也在弹出窗口中包含 content.js。您需要为弹出窗口使用不同的脚本。内容脚本在网页中运行。
标签: jquery google-chrome google-chrome-extension