I am making a chrome extension and I want to add an overlay navigation, but I need Javascript for that, and when I put the Javascript in, chrome told me I cannot use inline JS.
So then I used an event listener, but then it told me that it cannot read the even listener.
The navigation’s HTML:
<div id="Navigation" class="Overlay">
<a href="javascript:void(0)" id="closebtn">×</a>
<div class="Links">
<a href="popup.html"> Home </a>
<a href="colors.html"> Colors </a>
<a href="links.html"> Links </a>
</div>
</div>
<span id="menuIcon">
<div class="menuPart"></div>
<div class="menuPart"></div>
<div class="menuPart"></div>
</span>
The navigation’s EventListener (the JS):
document.getElementById("menuIcon").addEventListener("click", function(){
document.getElementById("Navigation").style.width = "100%"
});
document.getElementById("closebtn").addEventListener("click", function(){
document.getElementById("Navigation").style.width = "0%"
});
I have no idea what I’m doing wrong. Please help me.
2
Answers
You likely need to put some data into your manifest.json to build a content security policy that allows inline JS to run:
Chrome version 18+: How to allow inline scripting with a Content Security Policy?
https://www.w3.org/TR/CSP/#script-src-hash-usage
In a Chrome extension, you should use an external JavaScript file to add event listeners and manipulate the DOM.
Create a new JavaScript file, and name it something like overlay_nav.js or whatever you’d prefer.
Paste your JavaScript code into the .js file like the following example:
Now you’ll be able to link the .js file using a tag before the closing tag. See the example below:
Note that you’ll have to place the .js script in the same folder as the .html script