javascript - 为什么我的 Javascript Chrome 扩展代码不起作用? (循环检查按钮)

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

我正在尝试制作一个 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/

相关文章:

javascript - 当用户在表单上的文本框中键入内容时如何显示建议或相关名称

javascript - 使用CSS忽略div元素下nav的显示

带有显示 :none 的 div 中的 jQuery 轮播

javascript - 如何将变量从 javascript 传递到 symfony2 Controller

html - 如何更改表格 HTML/CSS 中 td 的默认值

python - 使用 soup.find() 提取特定的 html 项目

javascript - 如何查找 mongodb 中任何属性中包含 x 的所有结果?

javascript - 使用 CSS 均匀分布元素

javascript - jquery取消绑定(bind)点击不起作用

html - 设置 HTML5 视频大小?