Thursday, May 23, 2024
93
rated 0 times [  100] [ 7]  / answers: 1 / hits: 125828  / 12 Years ago, tue, november 27, 2012, 12:00:00

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/Firefox 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:


<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">
ha
</div>
<br />
<a onClick=hellYeah("xxx")>
hyhy
</a>
</body>
</html>

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.


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/"
]
}

More From » google-chrome-extension

 Answers
9

Chrome Extensions don't allow you to have inline JavaScript (documentation).

The same goes for Firefox WebExtensions (documentation).


You are going to have to do something similar to this:


Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), 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');
});
});

popup.js should be loaded as a separate script file:


<script src="popup.js"></script>

[#81769] Monday, November 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnyblaynes

Total Points: 667
Total Questions: 121
Total Answers: 102

Location: Anguilla
Member since Sat, Jan 23, 2021
3 Years ago
;