【发布时间】:2016-04-07 19:44:00
【问题描述】:
我需要迭代并单击页面上类.star_gray 的所有元素,并在重定向后保持迭代并单击继续。运行 JavaScript 代码不能满足第二个要求,所以我打算写一个 Chrome 扩展。
但我未能通过扩展程序模拟网页上的点击事件。我的项目如下:
manifest.json
{
"manifest_version": 2,
"name": "Check'em All",
"description": "",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"persistent": true,
"scripts": ["jquery.js", "background.js"]
},
"content_scripts": [{
"matches": ["file:///*"],
"js" : ["popup.js"]
}],
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Check'em All!</title>
</head>
<body>
<h1>Check'em All!</h1>
<button id="check-btn">BUTTON</button>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('check-btn');
btn.addEventListener('click', injectScript);
});
function injectScript() {
alert('Handler called!');
chrome.tabs.executeScript(null, { file: 'background.js' });
}
background.js
$(document).ready(function(){
$('.star_gray').click();
$('a.btn.page_next').click();
});
使用上面的代码,当我点击弹出窗口上的按钮(#check-btn)时,什么也没有发生。
【问题讨论】:
-
document.getElementById('#check-btn');是错误的。删除#符号。您可以将它与document.querySelector一起使用,因为它表示以下文本是一个id。但是,对于只查看元素 ID 的函数,这是多余的,而且是错误的。 -
@enhzflep 抱歉打错了。没有
#,代码仍然无法工作。 -
还没有接受的答案吗?
标签: javascript jquery google-chrome google-chrome-extension