简体   繁体   中英

How to execute a javascript command multiple times with single line of code in browser console?

I want to check if all ajax requests have completed and only then interact with element on a web page. Hence I opened chrome browser's developer console. And after entering url in search bar and hitting ENTER key, in console I keep hitting $.active multiple times and in results most of the time I can see returned value as 0 but some time as 1

I hit $.active command with hand hence I am not able to see consistent result all the time. Is there any java script code which I can enter in console and after hitting it, $.active command will be hit one by one till the number of times mentioned?

If $ is jQuery, you can add an ajaxComplete callback, and check if $.active inside:

$(document).on('ajaxComplete', () => {
  Promise.resolve().then(() => {
    if (!$.active) {
      console.log('All done');
    }
  });
});

It's not a single line of code, but it should work. (You can test it by running this in the console, then opening your inbox or reputation record in Stack Overflow's topbar. An ajax request will be sent out, and when it's complete, ajaxComplete will run, and $.active will get set to 0)

The Promise.resolve().then is needed because $.active gets decremented only after the ajaxComplete callback runs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM