skip to Main Content

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">&times;</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


  1. 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

    Login or Signup to reply.
  2. 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:

    // overlay_nav.js 
    document.getElementById("menuIcon").addEventListener("click", function(){ 
    enter code heredocument.getElementById("Navigation").style.width = "100%"; 
    }); 
    
    document.getElementById("closebtn").addEventListener("click", function(){ 
    document.getElementById("Navigation").style.width = "0%"; });
    

    Now you’ll be able to link the .js file using a tag before the closing tag. See the example below:

    <!-- popup.html or your relevant HTML file -->
    <!DOCTYPE html>
    <html>
    <head>
        <!-- Your other HTML head content goes here -->
    </head>
    <body>
        <!-- Your navigation and menu icon HTML goes here -->
    
        **<!-- Add the .js file here -->
        <script src="overlay_nav.js"></script>**
    </body>
    </html>
    

    Note that you’ll have to place the .js script in the same folder as the .html script

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search