[英]Why is my Javascript Chrome extension code not working? (Loop check for button)
I am trying to make a chrome extension that constantly checks for the button with the ID "product-addtocart-button", and as soon as it is found it will click. 我试图做一个chrome扩展程序,该扩展程序会不断检查ID为“ product-addtocart-button”的按钮,一旦找到该按钮,它就会单击。
I have came together with this javascript by learning and researching online. 通过在线学习和研究,我已经将此JavaScript一起使用。 I don't know much about javascript, so I don't really know what is going wrong.
我对javascript不太了解,所以我真的不知道出了什么问题。
My old javascript file was very bare and I had it set up so when I clicked the extension button, the button would be automatically clicked. 我的旧javascript文件非常裸露,我对其进行了设置,因此当我单击扩展按钮时,该按钮将被自动单击。
Code: 码:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,{
code: "document.getElementById('product-addtocart-button').click();"
});
});
Now, from research, I have (attempted to) added a function where after clicking the extension button the script would loop check for the actual extension and then once found, click it. 现在,通过研究,我(尝试)添加了一个功能,在该功能中,单击扩展按钮后,脚本将循环检查实际的扩展,然后在找到后单击该脚本。
background.js: 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);
}
}
});
});
When I click on the chrome extension button nothing happens. 当我点击Chrome扩展程序按钮时,什么也没有发生。 Any idea what is going on?
知道发生了什么吗?
According to specifications , you have to invoke executeScript like: 根据规范 ,您必须像这样调用executeScript:
chrome.tabs.executeScript(tab.id,{code:"yourCodePackedIntoOneString"});
or 要么
chrome.tabs.executeScript(tab.id,{file:"yourCodeFile.js"});
but you are calling: 但您正在打电话:
chrome.tabs.executeScript(tab.id,{function()etc...});
. 。
Try that and see how it goes. 尝试一下,看看效果如何。
Use content script file instead of background.js if you want to trigger the click for a specific page. 如果要触发特定页面的点击,请使用内容脚本文件而不是background.js。
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]
}
],
download JQuery into your local folder if you want to use JQuery . 如果要使用JQuery,请将JQuery下载到本地文件夹中。
if($('#product-addtocart-button').length>0)
$('#product-addtocart-button').click()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.