【问题标题】:Why is my Javascript Chrome extension code not working? (Loop check for button)为什么我的 Javascript Chrome 扩展代码不起作用? (循环检查按钮)
【发布时间】:2016-10-28 21:20:17
【问题描述】:

我正在尝试制作一个 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 扩展按钮时,没有任何反应。知道发生了什么吗?

【问题讨论】:

  • id是字符串,所以把document.querySelector(#product-addtocart-button)改成document.querySelector("#product-addtocart-button")
  • 嗨,如果这是我的新代码: chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(tab.id,{ function waitForElementToDisplay("#product-addtocart-按钮", 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); } } }); });还是什么都不做?
  • 你好像有语法错误,你不应该在function waitForElementToDisplay附近有{ ... }
  • 检查您的 Javascript 控制台是否有错误消息。
  • 定义函数时,形参必须是变量名,不能是字符串和整数。

标签: javascript jquery html google-chrome google-chrome-extension


【解决方案1】:

根据specifications,你必须像这样调用executeScript:

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

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

但你在打电话:

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

试试看效果如何。

【讨论】:

    【解决方案2】:

    如果您想触发特定页面的点击,请使用内容脚本文件而不是 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()
    

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多