1

In theory, if I set run_at, the .js that I use to select an element on the page should fire after the page is completely loaded. But it doesn't appear to be the case.

In my content.js, I have

    "content_scripts": [
        {
          "js": ["extensions/jquery-2.2.2.min.js", "content.js"],
          "run_at": "document_idle"
        }
      ]

In my content.js, I simply have:

alert("alert");
console.log("hello");
var fullname2 = $('#topcard').find('.profile-info').find('h1').text();
console.log(fullname2);

Both the alert and the first console.log works. The second console log doesn't log anything, because the selector failed to select anything. I know this because if I add a setTimeout for the content.js code block, and wait for 2 seconds, the second console log shows the fullname2 correctly.

Any idea why content.js is apparently firing before the page is fully loaded, such that the selector failed to find anything?

MichM
  • 886
  • 1
  • 12
  • 28
  • 1
    how is #topcard created? Dynamically? That might explain why it doesn't exist at document_idle – Cornwell May 18 '16 at 21:55
  • Have you tried `document_end`? – M. Foldager May 18 '16 at 22:41
  • As @Cornwell said, #topcard may be dynamically created, it would help a lot if you could provide the web page url. – Haibara Ai May 18 '16 at 23:48
  • Please don't post a question twice http://stackoverflow.com/questions/37308375/javascript-why-does-my-code-work-on-in-the-chrome-console-but-not-in-the-script – Haibara Ai May 18 '16 at 23:51
  • On one hand, Haibara is correct: you should probably edit an existing question unless it's already answered. On the other, it's not an exact duplicate, and this is actually a much cleaner question. My recommendation is to delete the old question. – Xan May 19 '16 at 09:30
  • There you go; I dupehammered it (since this iteration has an answer that applies to the old one as well) with keeping the newer/cleaner question as main. – Xan May 19 '16 at 09:34
  • Sounds good @Xan. Thanks! – MichM May 20 '16 at 14:14

1 Answers1

5

run_at: "document_idle" guarantees that the script is executed after DOMContentLoaded event that signals that all static DOM content is parsed and available.

If an element doesn't exist yet, this means that it's being added later dynamically, by the page's own code.

Obviously, Chrome has no way to predict when (if ever!) a page is in a "finished" state. You need to set your own criteria (like "when #topcard appears).

Having said that, your strategy should be as follows:

  1. Check if the element already exists. If it does, process it and you're done.

  2. Set up a listener for changes in the document. This is done through MutationObservers, and I highly recommend the mutation-summary library for simplicity.

Xan
  • 74,770
  • 16
  • 179
  • 206