Content_security_policy not work in my extension

In my content script I make a XHR request to get a audio url for my Audio() object to play. But in developer.mozilla.org webpage, I got a CSP warning, and the audio can not be played.
so ,in my manifest.json file, I just rewrite the default CSP police like this

  "content_security_policy": "script-src 'self' ; media-src https://openapi.youdao.com/; object-src 'self' *://*.youdao.com/*"

but it seems not work, I still got the CSP warning.
and this is my audio url https://openapi.youdao.com/ttsapi?q=once&langType=en&sign=DF8808E04044C6900DF696ED44D0DC8D&salt=1648873379040&voice=4&format=mp3&appKey=30b3aa18e38ef10f&ttsVoiceStrict=false

Web pages will have all kinds of CSP that will mess up your content script.

What should help is inject an “iframe” into the page and load your extension page (some “audio.html” file) into the iframe, then call the audio code in the iframe page.
That way the CSP of the page won’t apply to the code running inside the iframe.

Also, using CSP in the manifest file is dangerous and your addon may not pass review. So make sure to read this:

1 Like

OK,I will try this method. Thanks a lot.

by the way, could I use the shadow dom tech to solve this problem?

I don’t think that will help. It will encapsulate the HTML and CSS of the injected HTML but it doesn’t change the fact that your content script is being executed on the 3rd party webpage powered by CSP.
Unlike with iframe where your code is being executed as on the extension page, so the content_script limitations doesn’t apply anymore.

But I know, using iframe is not easy at all. For example if you want to send the iframe a message from the parent tab, you will have to send it first to background script and then forward it back to tab.

1 Like