javascript - 如何使用 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 攻击,因此之后调用的方法可能会运行恶意代码。
解决方案
推荐阅读
- android - Android(Kotlin) 应用程序在 Android 6 上运行完美,但使装有 Android 10 的设备崩溃
- perforce - 从软件仓库运行 Perforce Trigger 可执行文件
- reactjs - ReactJS - 数据不会从 axios 调用加载到下拉列表中
- python - 找到包含至少一个偶数的第 N 个数字
- sitecore - Sitecore 9.2 中内容作者和管理员的会话超时设置在哪里?
- android - 使用 exoplayer 从 byte[] 播放音频,从 jetpack 安全文件加密解密
- node.js - 使用 Fastify 的 Mongoose 多连接
- mysql - 如何创建如何在 typeorm 中创建多对多关系,[NestJS]
- qiskit - 如何获取默认的 EquivalenceLibrary?
- angular - Angular 9拦截器在导入特定组件时不起作用