2

I'm creating a Google chrome extension. The extension doesn't need to be active on all websites and thus instead of adding a "content_scripts" entry to manifest.json, I've added a "permissions" entry like this:

 "permissions": [
    "activetab"
  ]

I need to wait for DOM completion since my extension tries to get some data from DOM.

In my content script I've added the following code to wait for DOM creation:

window.addEventListener('DOMContentLoaded', function () {});

The problem is that the above trick works if somebody clicks my extension during page load, but if somebody opens my extension after the page has fully loaded, then my content script won't do anything, since the DOMContentLoaded event has already occured.

What should I do to make sure the code in my content-script fires irrespective of the fact that the page has loaded or not.

Kartik Anand
  • 3,957
  • 4
  • 39
  • 66
  • Just check document.readyState and if it's not complete, add an event listener, otherwise do the job immediately. I'm kinda surprised I couldn't find any simple answer for that after a quick search, I'll try again later. – wOxxOm Sep 12 '16 at 05:38
  • 1
    @wOxxOm I knew about the `document.readyState` thing but haven't really seen it being used at many places (Maybe I haven't seen a lot of code). I thought maybe a better solution exists (sigh!) – Kartik Anand Sep 12 '16 at 05:39
  • There nothing bad in it. With jQuery you can use $(function() { ... }) shortcut. – wOxxOm Sep 12 '16 at 05:42
  • @wOxxOm Did you figure out some other way? Maybe you should post your comment as answer instead :) – Kartik Anand Sep 12 '16 at 14:59
  • 1
    This is the standard vanilla js method, it just works, so I don't see any problems. As for posting an answer, I see at least two: [How to detect if DOMContentLoaded was fired](https://stackoverflow.com/a/35996985) and [$(document).ready equivalent without jQuery](https://stackoverflow.com/a/35659269) – wOxxOm Sep 12 '16 at 15:13
  • I believe `executeScript` still respects `runAt` parameter; therefore, in theory your script should be stalled until the default `document_idle` state is reached (which is guaranteed to be after `DOMContentLoaded`), so you don't need to wait in the content script. – Xan Sep 14 '16 at 12:04

0 Answers0