如何在WordPress中向内联脚本添加随机数

问题描述 投票:1回答:3

我正在尝试通过wp_add_inline_script和wp_localize_script向WordPress中插入的内联脚本添加一个nonce,但我无法弄清楚如何去做。它看起来没有WordPress过滤器。我的目标是为内联脚本设置一个nonce,因此我可以定义一个内容安全策略,该策略不会破坏插入内联脚本的常见插件。最后结果应该是这样的:

<script type="text/javascript" nonce="xxxxxxxxxx">....</script>

其中xxxxxxxx是nonce。

你有什么想法?

wordpress
3个回答
1
投票

尝试使用wp_enqueue_scripts钩子

function my_special_inline_script() {
    ?>
    <script>
        // your JS code
    </script>
    <?php
}

add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );

要么

function theme_prefix_enqueue_script() {
   wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );

1
投票

因为内联脚本的HTML是由WordPress代码生成的

sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )

您无法使用wp_add_inline_script()向HTML脚本元素添加属性,因为<script type='text/javascript'>是硬编码的。

但是,过滤器'script_loader_tag'将允许您在WordPress输出之前更改脚本元素的HTML。

请注意,过滤器'script_loader_tag'不会应用于通过调用wp_localize_script()添加的脚本元素,因为这些是由WordPress代码输出的:

echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";

由于这些是回显的并且<script type='text/javascript'>是硬编码的,因此无法向wp_localize_script()的HTML脚本元素添加属性。


0
投票

派对迟到了,但出于同样的原因,我只是遇到了这个问题。

我通过一些简单的wp_add_inline_script动作为str_replace解决了它。

add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );

function add_nonce_to_script_tag( $tag, $handle, $src ) {

  // Check the $handle and respond accordingly
  if ( $handle === 'my-script' ) {
    $nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
    $replace = sprintf("javascript' nonce='%s'>", $nonce_value );
    $tag = str_replace( "javascript'>", $replace, $tag);
  }

  return $tag;
}

// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');

加载内联脚本后,我看到带有nonce属性的script标记输出。这与我的内容安全策略一起工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.