Home > Software design >  Function inside "DOMContentLoaded" event does not get triggered
Function inside "DOMContentLoaded" event does not get triggered

Time:12-08

I was trying to create a chrome extension where the injected script should load right after the page has finished loading. Without the "DOMContentLoaded" event, the function does actually get triggered sometimes if the page loads fast enough. But as soon as I do something like this, the code never seems to get triggered:

document.addEventListener('DOMContentLoaded', () => {

  const wrapper = document.getElementById('<id>');
  const btn = document.createElement('button');

  btn.innerHTML = <Text>;
  wrapper.insertAdjacentElement('beforeend', btn);
  btn.addEventListener('click', () => {
    const el = document.getElementById('<id>').children;
   
  });
});

Is there something I'm doing wrong?

CodePudding user response:

Most likely because your code run too late, after DOMContentLoaded has already fired. if you're using jQuery you can do

$(document).ready(()=>{...})

and in vanilla-js you can do

{
    const cb = () => {...};
    if (document.readyState === "interactive" || document.readyState === "complete") {
        cb();
    } else {
        document.addEventListener('DOMContentLoaded', cb);
    }
}

CodePudding user response:

In your manifest.json file.
Add this line inside content_scripts "run_at": "document_end"

example

"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "all_frames": true,
        "js": ["contents/content.js"],
        "run_at": "document_end"
    }
],

Remove DOMcontentLoaded eventlistener.

You got error because: your event callback function set after "DOMContentLoaded" event triggered.

  • Related