Eric Gao
Eric Gao

Reputation: 3540

Chrome Extension DOMContentLoaded Not Firing

Right now I am trying to get the following code to run, but the console never logs 'added', only 'started'.

var addWebsiteAddress;
console.log('started');

document.addEventListener('DOMContentLoaded', function(){
  console.log('added');
  addWebsiteAddress = document.forms["addWebsiteAddress"];
  addWebsiteAddress.addEventListener('submit', addWebsite);

I've placed it in the HTML file as follows:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="popup.js" async></script>
    <title>Add a website to block</title>
  </head>
  <body>
    <form id="addWebsiteForm">
    Website Address: <input type="text" id="websiteAddress"><br>
    <input type="submit" value="Add Website">
    </form>
  </body>
</html>

What am I missing? DOMContentLoaded never seems to fire as I am unable to register the submit event as well.

Upvotes: 4

Views: 4384

Answers (2)

Ben Xu
Ben Xu

Reputation: 11

Maybe you set "run_at": "document_end" in manifest.json. Change "run_at": "document_end" to "run_at": "document_start". It works! I tried!

Upvotes: 1

Xan
Xan

Reputation: 77482

The culprit here is async attribute you're using.

Normally, when adding the <script> tag to the DOM, the browser will pause parsing the page to execute the script. With async, this is not guaranteed to be the case. It can be executed at an arbitrary point.

Your page is very small. Browser parses it nearly instantly and the event is fired before it "remembers" to execute your script - and as such it's not received by your script.

The idea behind async is not to stumble with the page loading as the script itself is loading. Since the resources in a Chrome extension are all local, loading times are not a factor, and as such you should not use it, opting for a more predictable program flow.

Upvotes: 4

Related Questions