Description
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.
Questions
- Is this considered insecure because another script could overwrite the values set via
wp_add_inline_script
to something malicious? - 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; }