我正在尝试制作一个 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();"
});
});
现在,通过研究,我(尝试)添加了一个功能,在单击扩展按钮后,脚本将循环检查实际扩展,然后一旦找到,单击它。
背景.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 扩展按钮时,没有任何反应。知道发生了什么吗?
最佳答案
根据specifications ,您必须像这样调用executeScript:
chrome.tabs.executeScript(tab.id,{code:"yourCodePackedIntoOneString"});
或
chrome.tabs.executeScript(tab.id,{file:"yourCodeFile.js"});
但你正在打电话:
chrome.tabs.executeScript(tab.id,{function()etc...});
。
尝试一下,看看效果如何。
关于javascript - 为什么我的 Javascript Chrome 扩展代码不起作用? (循环检查按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291947/