首页 > 解决方案 > 如何使用 Wordpress 中的方法防止 XSS 更改自定义全局 javascript 对象

问题描述

我正在处理 Wordpress 中的一个项目,该项目将多个 .js 文件排入队列,其中每个文件向全局 javascript 对象添加一个新方法,这是为了使所需的方法仅在满足某些条件时可用,例如is_page()、is_singular()、等等

除了避免使用多个全局函数污染窗口对象之外,以这种方式添加方法的目的主要是能够在使用诸如wp_localize_script()wp_add_inline_script()add_action( 'wp_footer', function_name )等。

每个 .js 文件内容都遵循添加方法的相同模式,如下所示:

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

在 Wordpress functions.php 文件中,内容如下所示:

// 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 这段代码工作得很好。我担心的是安全性,例如针对和 ALTER 最初由排队的 .js 文件创建的全局 globalFunctions 对象的 XSS 攻击,因此之后调用的方法可能会运行恶意代码。

标签: javascriptphpwordpressxssglobal

解决方案


推荐阅读