Skip to content
Advertisement

CSP and script localization in wordpress

I want to properly use Content Security Policy on my WordPress site, but also not hardcode URIs.

I am moving all my inline scripts to one file, and adding hashes to all script tags to use with Subresource Integrity.

The ajax localization gives me a hard time; It runs PHP to get the JS file name, and outputs it inline to an object (which gets used by ajax calls).

In order to make admin-ajax available, I have

JavaScript

Which outputs:

JavaScript

I need to be able to add a hash to this tag but I cannot find the right way.

I’m able to generate it in PHP like:

JavaScript

But I don’t know how to add this to the page correctly, and also, this feels too hacky.

Without either outputting this hash, or moving this object creation to my main JavaScript file, the page will not pass my CSP and script will not run.

How do I accomplish this?

Advertisement

Answer

As of this moment the only way I could solve it is by using [wp_enqueue_scripts][1], which is the hook used by [wp_enqueue_script][2] when utilizing [wp_localize_script][3]

Doesn’t feel like the best solution but it does work.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement