Chrome extension set to `run_at` `document_start` is running too fast?

后端 未结 2 1501
醉话见心
醉话见心 2020-12-08 22:10

EDIT: Something was wrong with my Chrome browser and creating a conflict with my script, a full reinstall eliminated whatever the problem source was. If I happen to find out

2条回答
  •  悲&欢浪女
    2020-12-08 23:08

    Your problem is that, when using "run_at": "document_start", the only element that is granted to exist in the DOM is the element. If you want to avoid errors relative to page load, like trying to access some element that hasn't been created yet, you'll have to either:

    • Make your script run at "document_idle" or "document_end". Although "document_end" still doesn't grant you that all the elements and resources of the page have been fully loaded (but the DOM has already been parsed), the "document_idle" keyword will give you the certainty that the DOM has been parsed and all the elements and resources have been loaded properly before your script runs.

    • Or, instead, you can continue using "document_start" wrapping your code inside a "DOMContentLoaded" listener, which will make it run when the DOM has completely finished loading and parsing, similarly to "document_idle". Here's an example:

      document.addEventListener("DOMContentLoaded", function() {
          // Run your code here...
      });
      

提交回复
热议问题