Warm tip: This article is reproduced from stackoverflow.com, please click
google-chrome google-chrome-extension javascript

Wait for Youtube comments to load then run function

发布于 2020-04-11 22:01:10

so you know those sites where you have to wait a certain quantity of time for a download button to appear after page has loaded. In this case like YouTube where the page finishes loading but you have to wait a certain amount of time for the comments to reveal as well. So the problem is I want my extention to run or atleast run a function when a certain div of the page finishes loading in the case the comments div. I've tried "run_at": "document_end" in my manifest file as some stackoverflows have said but it still doesn't do it after the comments load. I think it goes after page has finished loading but Youtube comments still load after. Some I'm surrently using something like setTimeout for 10000 milliseconds in my content.js file which works fine but the thing is some comments may load faster and some slower and I don't want one to wait long for the extension to load. Anyone got some help? Sorry for the long story.

runAfter = _=> alert('Hi');
// I want that function to run after the comment section div has finished loading.
// I could use setTimeout for 10 seconds but it seems long to wait eg.
setTimeout(_=> { alert('Hi') }, 10000);
Questioner
Mafia
Viewed
27
Ben Lorantfy 2020-02-05 01:23

You could try polling for visibility.

function waitForEl(el) {
  return new Promise((resolve, reject) => {
    const intervalId = setInterval(() => {
      if (document.querySelector(el)) {
        clearInterval(intervalId);
        resolve();
      }
    }, 500);
  });
}

waitForEl("#comments").then(() => {
  // comments should be loaded here
});