设置超时功能在 chrome 扩展程序弹出窗口.js问题

setTimeout function in chrome extension popup.js issues

本文关键字:窗口 js 问题 程序 扩展 超时 功能 chrome 设置      更新时间:2023-09-26

我有一个弹出窗口.js文件,其中包含一系列函数。我正在尝试运行一个设置为在创建新选项卡时运行的函数,但延迟很短。这是一个函数示例和我尝试过的解决方案。

// function.
function foo_bar()
{
 // some ajax call.
}
// try 1
setTimeout(foo_bar,1000);
EDIT:// executed without delay.
// try 2
setTimeout(function(){
//some ajax call.
},1000)
EDIT:// executed without delay.
// try 3
setTimeout(function(){
foo_bar();
},1000)
EDIT: // didn't seem to execute.
// try 4 and 5
window.addEventListener('load',foo_bar());
window.addEventListener('DOMContentLoaded',foo_bar());
// no delay takes place. The function completes before the page even loads.

// try 6
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {...}); 
// used the status from here to wait till page load is complete.
//problem with this is that sometimes the status doesn't get updated.
// try 7
// tried to delay the php script by using sleep(2), but ajax call would never complete.

谁能帮忙?不确定它是否有帮助,但脚本未定义为背景或内容。

编辑:更多细节。调用的函数正在执行对远程服务器的 ajax 调用,然后基于数据,使用 chrome.tabs.executeScript 操作新选项卡登陆的页面。唯一的问题是,页面有一半时间没有准备好。

尝试 4 和 5 应该是:

window.addEventListener('load',foo_bar);
window.addEventListener('DOMContentLoaded',foo_bar);

没有发生延迟,因为您以内联方式调用它们。