1

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

  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; } 

    1 Answer 1

    0

    Using wp_kses_post to escape the texts before setting them in wp_add_inline_script is a good approach to prevent malicious content from being added to the page. This will ensure that the text is properly sanitized and only contains allowed HTML tags and attributes.

    If you want to allow certain HTML tags and attributes, you can use wp_kses instead of wp_kses_post and pass an array of allowed tags and attributes as a second argument.

    Using element.innerHTML to set the contents of the elements is generally safe, as long as the content being set has been properly sanitized. In this case, since you are using wp_kses_post (or wp_kses with an appropriate set of allowed tags and attributes) to sanitize the text, it should be safe to use element.innerHTML.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.