wp enqueue script – How to securely set dynamic HTML content with JavaScript?



I have implemented a frontend script that gets a few text options from the server via wp_add_inline_script.

When the user does an action the content should dynamically change to one of the given texts.
I want to allow HTML in these texts.

Currently, I’m escaping the texts with wp_kses_post before setting them in wp_add_inline_script.
Then in the frontend I use element.innerHTML to overwrite the contents of some elements.


  1. Is this considered insecure because another script could overwrite the values set via wp_add_inline_script to something malicious?
  2. Is there a better (more secure) alternative?

Example code

Somewhere in the backend:

// These can be configured by an admin.
$texts = array(
    'loading' => '<p><i>Please wait...</i></p>',
    'error'   => '<p>Something went wrong...</p>',
    'success' => '<p><b>It worked! This is your %value%!</b></p>',
$json = wp_json_encode( $texts );
wp_add_inline_script( SCRIPT_HANDLE, "const myPluginTexts = $json", 'before' );
wp_enqueue_script( SCRIPT_HANDLE );

Somewhere in the frontend:

element.innerHTML = myPluginTexts.loading;
// Do something resulting in `success` and `value` being set.
if ( success ) {
    element.innerHTML = myPluginTexts.success.replace('%value%', value);
} else {
    element.innerHTML = myPluginTexts.error;

Josef Wittmann 2 months 2022-12-14T20:59:05-05:00 0 Answers 0 views 0

Leave an answer