我是javascript的新手并为自己编写了一个脚本
问题:实际脚本完成后,在重新加载页面之前应该有5秒的超时时间。脚本忽略超时,重新加载后URL中的#标签丢失。循环停止,因为标签已经消失。
我尝试了什么:
setTimeout(location.reload(true);}, 5000);
window.setTimeout(location.reload(true);}, 5000);
setTimeout(window.open("https://MyLink.com/#script","_self");}, 5000);
所有这些都以某种方式立即执行(没有5秒钟休息),并在没有主题标签(甚至是最后一个)的情况下调出页面,导致循环停止。
content.js中的完整代码: (另外在pastebin上:http://pastebin.com/ey32SzBP)
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
if(window.location.hash=="#script") {
var oneKeyOnly = true;
function checkItem() {
var itemsArray = ["Apples", "Bananas", "Oranges", ];
var matchingItems = [];
var x = document.getElementsByClassName("item");
for(var y = 0; y < x.length; y++){
if(itemsArray.indexOf(x[y].getAttribute("data-name")) >= 0){
var id = x[y].getElementsByClassName("item-checkbox")[0].getAttribute("id");
matchingItems.push(id);
}
}
return matchingItems;
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'submit' && buttons[i].value == val)
{
buttons[i].click();
console.log("Trying to withdraw!");
break;
}
}
}
var result = checkItem();
var lengthOfArray = result.length - 1;
if (oneKeyOnly == true) {
var rand = randomIntFromInterval(0,lengthOfArray);
document.getElementById(result[rand]).checked = true
console.log("Found: " + result[rand]);
}
else {
for(index=0, len = result.length; index < len; ++index) {
document.getElementById(result[index]).checked = true
keynr = index + 1;
console.log("Found " + result.length + " fruits - Selected Nr. " + keynr + "!");
}
}
clickButton("Withdraw selected items");
setTimeout(location.reload(true);}, 5000);
}
}
}, 10);
});
如果有任何不清楚的地方,请告诉我!
答案 0 :(得分:1)
尝试将reload方法包装在匿名函数中,如此
setTimeout((function(){location.reload(true)}), 5000);