0

I am making a Chrome extension that needs JavaScript. How can I include JavaScript in my Chrome extension?

This is the popup.Json as it has requested me to do.

function AddNewPopup() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

And here is the script tool that it keeps blocking.
<div class="popup" onclick="AddNewPopup()"><button class="addnew"><span class="popuptext" id="myPopup">Test for 0.9</span><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSH-bdYc7hZzKrjl7v1tMC2qEwo7F_3HgFWyQ&usqp=CAU" width="50"></button></div>

Please tell me how to get rid of this security issue and insert my JavaScript.

1 Answers1

1

Having an onclick handler in your html like that (an example of inline javascript) is not allowed in extensions.

To get it to work you'll need to include popup.js from your html and from within popup.js register the onclick hander like so:

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

popup.js:

document.getElementById('myPopup').addEventListener("click", AddNewPopup);

You can read more about that error in this article here: https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution

dwosk
  • 1,202
  • 8
  • 11
  • Hmm, it didn't work. Do i put the script around the button i had? It's not working. – Cruze Headphones Oct 02 '20 at 18:06
  • Add `` above the `
    ...
    ` line you have. Then in popup.js register the click listener. You'll need to remove the `onclick="AddNewPopup()"` that you have. https://stackoverflow.com/questions/36324333/refused-to-execute-inline-event-handler-because-it-violates-csp-sandbox
    – dwosk Oct 02 '20 at 18:09
  • Um, it still didn't work. – Cruze Headphones Oct 02 '20 at 18:17
  • Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. ``` ``` – Cruze Headphones Oct 02 '20 at 18:23
  • It stopped the moment it saw "script". I really need to add this or else my extension will not function. – Cruze Headphones Oct 02 '20 at 18:27
  • That's weird - the chrome link I posted in my original answer details this very use case. – dwosk Oct 02 '20 at 18:30
  • Yeah, I consulted the website and it didn't work either. – Cruze Headphones Oct 02 '20 at 19:00
  • @CruzeHeadphones Were you able to resolve this issue? I'm facing the same in my angular app. – Evan MJ Mar 16 '23 at 09:56