Search code examples
google-chrome-extensionmanifestcontent-security-policychrome-extension-manifest-v3

javascript click function causes Content Security Policy error


One of my chrome extension content scripts is executing a click function on an element like this

var currencySelectorLink = document.getElementById('switcher-info'); currencySelectorLink.click();

However the last line is causing the following error:

Refused to run the JavaScript URL 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've spend multiple hours now trying to figure this out, maybe some of you will have an idea how to fix it. I absolutely have to trigger this click event, there is no way around it

EDIT: After some more investigation I found out that it happens, because the link has href attribute with inline javascript:

<a class="switcher-info notranslate" href="javascript:void(0)" id="switcher-info"></a>

anybody has any ideas how to bypass that? If I do this:

currencySelectorLink.href= '#' ;

then error is gone, but it breaks website functionality and not exactly expected behavior comes out of this click event


Solution

  • All that the <a href="javascript:void(0)" code does is to prevent following on the link. You can do the same more pretty way:

    currencySelectorLink.href= '#' ;
    currencySelectorLink.addEventListener("click", function(event) {
      event.preventDefault();  // Prevent default action (a following a link)
      }, false);
    

    Note. Since you call click() you already have some event handler. You can insert event.preventDefault(); into it instead of add a second handler. And use:

    <a class="switcher-info notranslate" href="#" id="switcher-info"></a>

    without javascript:void(0).