我想做一個不斷檢查ID爲「product-addtocart-button」的按鈕的chrome擴展,只要發現它會點擊。爲什麼我的Javascript Chrome擴展程序代碼無法正常工作? (循環檢查按鈕)
我已經通過在線學習和研究這個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擴展按鈕,沒有任何反應。任何想法是怎麼回事?
的ID是字符串,那麼用'document.querySelector( 「#產品addtocart鍵」)改變'document.querySelector(#產品addtocart-button')' –
嗨,如果這是我的新代碼: chrome.browserAction.onClicked.addListener(function(tab){chrome.tabs.executeScript(tab.id,{ function waitForElementToDisplay(「#product-addtocart-button」,10){document.querySelector(「產品addtocart鍵 「)= NULL)!{ 警報(」 的document.getElementById( '產品addtocart按鈕')點擊()「) 回報; } 其他{ 的setTimeout(函數(){ waitForElementToDisplay(「#產品ADDT ocart-button「,10); 10); } } \t \t}); }); 它仍然無所作爲? –
你似乎有一個語法錯誤,你不應該有'{...}'around'函數waitForElementToDisplay' – Barmar