假设网站上有一个字符串'Click me'。假设它是使用JavaScript的链接,我需要点击该文本。我正在构建一个chrome扩展来这样做。但我的代码并不适用于所有情况。
到目前为止,这是我的代码。
的manifest.json
{
"manifest_version": 2,
"name": "Such Activity",
"description": "Wow",
"version": "1.0",
"permissions": ["tabs", "<all_urls>"],
"browser_action": {
"default_icon": {
"19": "images/icons/19.png",
"38": "images/icons/38.png"
},
"default_popup": "popup.html"
},
"icons": {
"16": "images/icons/16.png",
"19": "images/icons/19.png",
"38": "images/icons/38.png",
"64": "images/icons/64.png",
"128": "images/icons/128.png"
}
}
popup.js
function injectTheScript() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// query the active tab, which will be only one tab
//and inject the script in it
chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript);
content_script.js
function clickSome() {
function getElementsByText(text) {
function rec(ele, arr)
{
if (ele.childNodes.length > 0)
for (var i = 0; i < ele.childNodes.length; i++)
rec(ele.childNodes[i], arr);
else if (ele.nodeType == Node.TEXT_NODE &&
ele.nodeValue.indexOf(text) != -1)
arr.push(ele.parentNode);
return arr;
}
return rec(document.body, []);
}
var x = 'Text';
var my = getElementsByText(x.ignoreCase);
var mod =my[0].className;
console.log(my);
document.getElementsByClassName(mod)[0].click();
}
clickSome();
popup.html
<!doctype html>
<html>
<head><title>activity</title></head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>