Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

javascript - chrome extension: the js script fires too early despite run_at: document_idle

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...