1

我想做一個不斷檢查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擴展按鈕,沒有任何反應。任何想法是怎麼回事?

+0

的ID是字符串,那麼用'document.querySelector( 「#產品addtocart鍵」)改變'document.querySelector(#產品addtocart-button')' –

+0

嗨,如果這是我的新代碼: 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}); }); 它仍然無所作爲? –

+0

你似乎有一個語法錯誤,你不應該有'{...}'around'函數waitForElementToDisplay' – Barmar

回答

-1

如果要觸發特定頁面的點擊,請使用內容腳本文件而不是background.js。

"content_scripts": [ 
    { 
     "matches": ["http://www.google.com/*"], 
     "css": ["mystyles.css"], 
     "js": ["jquery.js", "myscript.js"] 
    } 
    ], 

如果您想使用JQuery,請將JQuery下載到本地文件夾中。

if($('#product-addtocart-button').length>0) 
$('#product-addtocart-button').click() 
0

specifications,你必須調用executeScript,如:

chrome.tabs.executeScript(tab.id,{code:"yourCodePackedIntoOneString"});

chrome.tabs.executeScript(tab.id,{file:"yourCodeFile.js"});

,但你在呼喚:

chrome.tabs.executeScript(tab.id,{function()etc...});

試試看看它是怎麼回事。

相關問題