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

时间:2018-06-05 06:34:48

标签: wordpress

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

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

其中xxxxxxxx是nonce。

你有什么想法吗?

3 个答案:

答案 0 :(得分:1)

尝试使用wp_enqueue_scripts hook

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 :(得分:1)

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

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

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

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

请注意,过滤器&#39; script_loader_tag&#39;将不会应用于通过调用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脚本元素中。

答案 2 :(得分: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');

一旦内联脚本加载,我将看到带有随机数属性的script标记输出。这与我的Content-Security-Policy配合正常。