I’m building a Google Chrome extension that manages bookmarks on the new tab page. Everything works fine except for an issue with the removal of bookmarks from the favorites list. When I click the “delete” option in the dropdown, nothing happens, and I noticed that my console is throwing a Content Security Policy (CSP) error.
I understand that Chrome extensions enforce a strict CSP and disallow inline event handlers, but I’m struggling to find the correct way to resolve this issue. I would like to avoid using unsafe-inline due to security concerns.
Here is the specific error I’m receiving in the console:
Refused to execute inline event handler because it violates the
following Content Security Policy directive: “script-src ‘self'”.
Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce
(‘nonce-…’) is required to enable inline execution. Note that hashes
do not apply to event handlers, style attributes, and javascript:
navigations unless the ‘unsafe-hashes’ keyword is present.
I understand that this happens due to the use of inline event handlers (like onclick), but I’m not sure how to restructure my code to avoid this problem.
What I’ve tried:
-
I attempted to modify my manifest.json to allow inline scripts by adding unsafe-inline, but I want to avoid this due to security risks.
-
I tried using external JavaScript (script.js) to handle events via addEventListener(), but something seems to be missing or incorrectly set up.
{ "manifest_version": 3, "name": "My Bookmarks Manager", "version": "1.0", "description": "Manage your bookmarks on the new tab page.", "permissions": ["bookmarks"], "chrome_url_overrides": { "newtab": "newtab.html" }, "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self';" } } <div id="favoritesContainer" class="mt-4"></div> <!-- Dropdown in card for deletion --> <ul class="dropdown-menu"> <li><a class="dropdown-item text-danger" href="#" id="delete-123">Delete</a>. </li> </ul> document.getElementById('delete-123').addEventListener('click', function(event) { event.preventDefault(); event.stopPropagation(); deleteFavorite('123'); // Call the function to delete the bookmark }); function deleteFavorite(url) { let favorites = getFavorites(); favorites = favorites.filter(fav => fav.url !== url); localStorage.setItem('favorites', JSON.stringify(favorites)); renderFavorites(); // Refresh the list }
I believe the issue lies with the CSP blocking inline event handlers, and possibly how I’m trying to remove bookmarks. I’m not sure if there’s a better way to add event listeners in my script.js or if I need to restructure my code to comply with the security policy.
How can I solve this issue without using unsafe-inline in my CSP?
Any guidance or suggestions would be greatly appreciated!