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

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

8
  • Hmm, it didn't work. Do i put the script around the button i had? It's not working. Oct 2, 2020 at 18:06
  • Add <script src="popup.js"></script> above the <div>...</div> line you have. Then in popup.js register the click listener. You'll need to remove the onclick="AddNewPopup()" that you have. stackoverflow.com/questions/36324333/…
    – dwosk
    Oct 2, 2020 at 18:09
  • Um, it still didn't work. <script src="popup.js"></script> <div class="popup"><button class="addnew"><span class="popuptext" id="myPopup">Test for 0.9</span><img src="encrypted-tbn0.gstatic.com/…" width="50"></button></div> Oct 2, 2020 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. <script src="popup.js"></script> Oct 2, 2020 at 18:23
  • It stopped the moment it saw "script". I really need to add this or else my extension will not function. Oct 2, 2020 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.