我正在尝试使一个chrome扩展,不断检查与ID "product-addtocart-button"按钮,并一旦发现它会点击。
我通过在线学习和研究来学习这个javascript。我对javascript了解不多,所以我真的不知道哪里出了问题。
我的旧javascript文件是非常裸露的,我有它的设置,所以当我点击扩展按钮,按钮会自动点击。
代码:chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,{
code: "document.getElementById('product-addtocart-button').click();"
});
});
现在,从研究中,我已经(试图)添加了一个功能,在单击扩展按钮后,脚本将循环检查实际扩展,然后一旦找到,单击它。
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,{
function waitForElementToDisplay(#product-addtocart-button, 10) {
if(document.querySelector(#product-addtocart-button)!=null) {
alert("document.getElementById('product-addtocart-button').click()")
return;
}
else {
setTimeout(function() {
waitForElementToDisplay(#product-addtocart-button, 10);
}, 10);
}
}
});
});
当我点击chrome扩展按钮什么都没有发生。知道是怎么回事吗?
根据规范,您必须像这样调用executeScript:
chrome.tabs.executeScript(tab.id,{code:"yourCodePackedIntoOneString"});
或
chrome.tabs.executeScript(tab.id,{file:"yourCodeFile.js"});
但是你正在打电话:
chrome.tabs.executeScript(tab.id,{function()etc...});
.
试一下,看看效果如何
如果你想触发特定页面的点击,使用内容脚本文件而不是background.js。
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]
}
],
如果你想使用JQuery,请下载到你的本地文件夹。
if($('#product-addtocart-button').length>0)
$('#product-addtocart-button').click()