我正在从事一个Wordpress中的项目,该项目将多个.js文件排队,其中每个文件都向全局javascript对象添加一个新方法,这是为了使所需的方法只有在满足某些条件(如is_page()、is_singular()等)时才可用。
以这种方式添加这些方法的目的除了避免使用多个全局函数来污染窗口对象之外,主要是为了能够在内联javascript中调用这些方法,这些javascript与wordpress函数(如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 );
}
?>这段代码运行得非常好。我担心的是安全性,比如在XSS攻击中,首先由排队的globalFunctions文件创建并更改全局.js对象,因此以后调用的方法可能会运行恶意代码。
发布于 2021-03-22 05:17:55
你没有做任何不寻常或不安全的事。您只是定义函数,这对于JavaScript来说是一件非常正常和合理的事情。如果您的页面上运行着恶意脚本,那么当然,它可以重新定义这些方法,但是它还可以做其他更糟糕的事情。
这就是为什么您需要确保恶意脚本不能使用清理和转义等基本实践在页面上运行。没有关于不定义函数的最佳实践。如果你不应该那样做的话,JavaScript根本就不会工作。
https://wordpress.stackexchange.com/questions/385493
复制相似问题