php – How to prevent XSS alter custom global javascript object & methods in WordPress

Question

Im working on a project in WordPress that enqueues multiple .js files where each file adds
a new method to a global javascript object, this in order to make the desired methods available only if certain conditions are met like is_page(), is_singular(), etc.

The purpose of adding the methods in this way besides avoiding polluting the window object with multiple global functions is mainly to be able to call this methods in a inline javascript added dinamically with
wordpress functions like wp_localize_script(), or wp_add_inline_script(), or add_action( ‘wp_footer’, function_name ), etc.

Each .js file content follows the same pattern of adding the method like so:

(function(){
    if( typeof globalFunctions === 'undefined' ){ // If global object doesn't exist create empty global object.
        window.globalFunctions = {};
    }

    globalFunctions.method1 = function( name ){  // once object is created add method.
        console.log( 'My name is ' + name );
    }
})();

In WordPress functions.php file the content would be like so:

// FIRST STEP REGISTERING AND ENQUEUEING SCRIPTS IN FOOTER
function add_js_files_fn() {

    wp_register_script( 'method-1', get_template_directory_uri() . '/js/method-1.js', array(), null, true );
    wp_register_script( 'method-2', get_template_directory_uri() . '/js/method-2.js', array(), null, true );
    wp_register_script( 'method-3', get_template_directory_uri() . '/js/method-3.js', array(), null, true );

    // this conditional only makes method 1 available if visited page has slug of 'page-slug-example'
    if ( is_page( 'page-slug-example' ) ) {  
        wp_enqueue_script( 'method-1' );
    }

    wp_enqueue_script( 'method-2' ); // this line makes method 2 available in any page or post
    wp_enqueue_script( 'method-3' ); // this line makes method 3 available in any page or post
}

add_action( 'wp_enqueue_scripts', 'add_js_files_fn' );

// SECOND STEP CALLING METHOD WITH INLINE JAVASCRIPT IF IS A CERTAIN PAGE
if ( is_page( 'page-slug-example' ) ) { 

    add_action( 'wp_footer', function() { ?>

        <script type="text/javascript">
        (function(){

            globalFunctions.method1('John Doe'); // Outputs My Name is John Doe

        });
        </script>

    <?php }, 999 ); 
}
?>

Altought this code works perfectly fine. My concern its about security, like in case of an XSS attack that targets and ALTER the global globalFunctions object that first was created by the enqueued .js files, thus the methods when called afterwards potentially could run malicious code.

0
Pappageorgio 4 months 2021-03-21T23:57:08-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse