Saturday 22 April 2017

javascript - onClick within Chrome Extension not working



This seems to be the easiest thing to do, but it's just not working. In a normal browser the .html and .js files works perfectly, but in the Chrome extension the onClick function is not performing what it's supposed to do.




.js file:



function hellYeah(text) {
document.getElementById("text-holder").innerHTML = text;
}


.html file:







<br/> Getting Started Extension's Popup<br/>




ha




hyhy





So basically once the user clicks "hyhy", "ha" should change into "xxx". And again - it works perfectly in the browser but does not work in the extension. Do you know why? Just in case I'm attaching the manifest.json below as well.




Thanks in advance!



manifest.json:



{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"http://api.flickr.com/"
]
}

Answer




Chrome Extensions don't allow you to have inline JavaScript (documentation). You are going to have to do something similar to this.



Assign an ID to the link ( becomes ), and use addEventListener to bind the event. Put the following in your popup.js file:



document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});

});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...