Reputation: 2382
Unlike other similar posts where they had code issues (SO1, SO2), I am no longer getting a
Uncaught TypeError: Cannot read property 'addEventListener' of null
as I am using document.onload()
so their solution didn't help
My code:
popup.html
<button class="submit" id='checkButton'>
Submit
</button>
<script type="text/javascript" src="./content.js"></script>
<script type="text/javascript" src="/background.js"></script>
Background.js
function submit(){
alert('loaded')
}
document.onload = function(){
document.getElementById("checkButton").addEventListener("click", submit);
console.log('loaded')
}
manifest.json
{
"manifest_version": 2,
"name": "To be named",
"description": "This extension helps...",
"version": "0.1.0",
"browser_action":{
"default_popup":"popup.html"
},
"permissions": [
"storage",
"identity",
"identity.email",
"http://127.0.0.1:5000/test",
"http://127.0.0.1:5000/get/info",
"http://127.0.0.1:5000/test",
"http://0.0.0.0:5000/test",
"http://127.0.0.1:5000/Time"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["https://www.blank.org/"],
"js": ["content.js"],
"css": ["styles.css"]
}]
}
Yet, when I click on submit from extension. I don't get any 'loaded' (same applies if I move func to content.js) nor do I get any error in my chrome://extemsion as mentioned.
Upvotes: 0
Views: 239
Reputation: 114
I'm no expert, but I think the problem is your trying to edit the popup.html DOM from a background script. That won't work. Instead try this:
background.js:
//Your other javascript...
var views = chrome.extension.getViews({
type: "popup"
});
for (var i = 0; i < views.length; i++) {
views[i].document.getElementById('checkButton').addEventListener("click", submit);
console.log("loaded");
}
I'm assuming this as if you were using the background.js as a background script. I don't see why you're including background.js in the bottom of popup.html, though. Here's what I suggest:
popup.html:
<button class="submit" id='checkButton'>
Submit
</button>
<script type="text/javascript" src="./popup.js"></script>
popup.js:
function submit(){
alert('loaded')
}
document.onload = function() {
document.getElementById("checkButton").addEventListener("click", submit);
console.log('loaded')
}
Hope this works! :)
Upvotes: 1