2016-10-28 22 views
-1

我想創建一個Chrome擴展,一旦我點擊鉻擴展,腳本將啓動,並將循環檢查每個1毫秒的ID爲「product-addtocart-button」 。所以,一旦循環找到按鈕,它需要立即點擊。Chrome擴展循環檢查按鈕錯誤

manifest.json的:

{ 
    "description": "Click a button with ID=product-addtocart-button", 
    "manifest_version": 2, 
    "name": "click-product-addtocart-button", 
    "version": "0.1", 

    "permissions": [ 
     "activeTab" 
    ], 

    "background": { 
     "scripts": [ 
      "background.js" 
     ] 
    }, 

    "browser_action": { 
     "default_icon": { 
      "32": "icon.png" 
     }, 
     "default_title": "Click product-addtocart-button" 
    } 
} 

background.js:

var button = document.getElementById("product-addtocart-button"); 
var time = 10; 

chrome.browserAction.onClicked.addListener(function(tab) 
    { 
    chrome.tabs.executeScript(tab[0], 

     function waitForElementToDisplay(button, time) { 
       if(document.querySelector(button)!=null) 
       { 
        document.getElementById(button).click(); 
        return; 
       } 
       else 
       { 
        setTimeout(function() { 
         waitForElementToDisplay(button, time); 
        }, time); 
       } 
      } 
     ); 
    } 
); 

popup.html:

<!doctype html> 
<html> 
    <head> 
    <title>Getting Started Extension's Popup</title> 
    <style> 
     body { 

     } 
     #status { 

     } 
    </style> 

      <script src="popup.js"></script> 
    </head> 
    <body> 
    </body> 
</html> 

我得到這些錯誤:

Error in event handler for browserAction.onClicked:

*指向我這個: Pic1 然後,這個錯誤

Error: Invocation of form tabs.executeScript(undefined, function) doesn't match definition tabs.executeScript(optional integer tabId, object details, optional function callback)

*指向我這個: Pic2

我該怎麼辦?

回答

0

回答這個問題第3次(請停止發佈了同樣的問題新的問題):

specifications,你必須調用executeScript,如:

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

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

但是您打電話給:

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

試試這個:

有一個文件名爲myWaitingLoop.js

function waitForElementToDisplay(){ 
    var button = document.querySelector("#product-addtocart-button"); 
    if (button){ 
     button.click(); 
    } else { 
     setTimeout(waitForElementToDisplay,100); 
    } 
} 
waitForElementToDisplay(); 

,然後在你的background.js腳本:

chrome.browserAction.onClicked.addListener(function(tab){ 
    chrome.tabs.executeScript(tab.id,{file:"myWaitingLoop.js"}); 
}); 
+0

你是一個傳奇的人! !正是我想要的。我一直在張貼,因爲我害怕沒有人會看到這個問題,根據我在不同的時間區域(阿拉伯聯合酋長國)和美國的時差在任何人都看不到。非常感謝迪拜:) –

+1

如果答案是正確的,請將其標記爲已接受的答案。 –

+0

對不起,我已經在其他問題上。 –