Timothy Lee
Timothy Lee

Reputation: 1

Chrome Extension addEventListener null

I just started learning JS a few weeks ago and am trying to build a Chrome Extension. I've build a manifest.json, popup.html, popup.js, and content.js file.

When I try running the background page console on Chrome to see if the popup.js is working I keep getting the error:

Uncaught TypeError: Cannot read property 'addEventListener' of null
at popup.js:8

I've tried moving the script in the html to the bottom of the body, but it still ends in an error and have tried implementing:

document.addEventListener('DOMContentLoaded', function () {
    //   My code here.. ( Your code here  )
    }); 

in my popup.js and the windows.onload method, but still haven't been able to get rid of the error.

If someone could please point out any errors in my code and tell me what is wrong I would really appreciate it. Thanks

POPUP HTML

<!DOCTYPE html>
<html>
<head>
    <title>Like IG Links</title>
</head>

<body>

    <h3><center>Paste Links Below</center></h3>
    <hr>
    <textarea rows="10" cols="60" id="urls"></textarea>
    <br>
    <textarea rows="1" cols="5" id="counter" disabled></textarea>
    <br>
    <br>

    <button type="submit" align="center" style="width:60px;"
            id="start">Start</button>

    <br> 
    <br>

    <button type="submit" align="right" style="width:60px;"
            id="stop">Stop</button>          

   <script type="text/javascript" src="popup.js"></script>              

</body>

</html>

CONTENT JS

console.log('CHROME');

POPUP JS

console.log('background running');

function loadUrls() {
console.log("123");
}

var startbutton = document.getElementById("start");
startbutton.addEventListener('click', loadUrls);    

MANIFEST JSON

{ 
"manifest_version": 2,      
"name": "Like IG Links",
"version": "1.0",    
"description": "Like IG Links",

"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": ["content.js"]
    }    
],

"background": {
    "scripts": ["popup.js"]
    },

"browser_action": {
"default_icon": "icon.png",  
"default_popup": "popup.html"                 
},

"permissions": ["tabs", "storage", "activeTab"]
}

Upvotes: 0

Views: 1509

Answers (1)

ChairForceOne
ChairForceOne

Reputation: 21

Remove the background script portion of the manifest. After updating the extension, the errors should disappear. In an extension I am working on, I had jquery.js and popup.js in the HTML and in the manifest. The background script tag for the manifest is for logic that tracks browser events and responds to them persistently, not for the js behind the extension HTML.

Upvotes: 1

Related Questions