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

折月煮酒 提交于 2020-01-17 04:44:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37308375/javascript-why-does-my-code-work-on-in-the-chrome-console-but-not-in-the-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!