Make WordPress Core

Opened 3 years ago

Last modified 4 days ago

#59446 accepted defect (bug)

Use script helper functions in admin to enable Content-Security-Policy opt-in

Reported by: westonruter Owned by: westonruter
Priority: normal Milestone: 7.3
Component: Administration Version: 5.7
Severity: normal Keywords: has-patch has-unit-tests
Cc: Focuses: javascript

Description (last modified by westonruter)

In #58664 the script helper functions—wp_get_script_tag(), wp_print_inline_script_tag(), wp_get_inline_script_tag()—were leveraged to eliminate manual construction of script tags on the frontend and the login screen. These were introduced in #39941. This made it possible to opt-in (see ​example plugin) to a Strict Content-Security-Policy (​Strict CSP) to guard against any possible XSS exploits. The scope in #58664 was limited to the frontend and the login screen because of the sheer number of inline scripts printed on the wp-admin. Additionally, the site editor and block editors make use of dynamically-constructed script tags in the editor iframe which is a Strict CSP violation.

Much of the work to rework inline scripts to use wp_print_inline_script() in the admin can be seen in an ​existing PR (now stale) from @enricocarraro.

See also #59444 which is about how to improve the developer experience of working with these JavaScript string literals.

Change History (53)

This ticket was mentioned in ​Slack in #core-performance by westonruter. ​View the logs.


3 years ago

#2 follow-up: @anonymized_14808221
3 years ago

Can I ask a clarification? I am confused on the "version" of this trac
It says 5.7 and the selector only allows up to 5.7.2

Yet the trac was opened just 5 weeks ago, during a 6.x WP Version "timeframe". I am confused :)

What I am ultimately wondering is if there are ways already available for the _backend_ to become CSP ready, or if we only yet have https://core.trac.wordpress.org/ticket/39941 which implemented a front end filter allowing us to somewhat filter those script tags and add a nonce...

Thank you for any information!

#3 in reply to: ↑ 2 ; follow-up: @westonruter
3 years ago

Replying to bedas:

Can I ask a clarification? I am confused on the "version" of this trac
It says 5.7 and the selector only allows up to 5.7.2

Good question. The version field here refers to when the first applicable version of WordPress that the issue is relevant to. Since the functions were introduced in 5.7, that's why this version is used.

The target version for fixing the issue is captured in the "milestone" field, which is still just Future Release. There isn't currently an established way to opt-in to CSP for the backend, so that's what this ticket is for.

#4 in reply to: ↑ 3 ; follow-up: @anonymized_14808221
3 years ago

Replying to westonruter:

Thanks! Makes sense now.

I guess then there is some issue with wp_inline_script_attributes, because if it is intended for front end, then it shouldn't run in the backend - but does, and misses the array key type in that case.
I also notice that the documentation for the related wp_get_inline_script_tag is wrongly saying to use wp_script_attributes to filter the tags.

I guess I will open a commit/trac for the latter one and, should I open a trac for the first one? the very least we would need to specify on the doc page that this needs to be hooked explicitly to front end, or that an isset() should be run (which IMO is quite uncommon for filters/hooks, usually they run only where the data is available)

Finally, what about style tag? This is as far I see also not yet implemented (neither in the front nor in the backend)
Is there already a trac for that?

Please stop me if I am wrong. Thanks!

Last edited 3 years ago by anonymized_14808221 (previous) (diff)

#5 in reply to: ↑ 4 @westonruter
3 years ago

Replying to bedas:

Replying to westonruter:
I guess then there is some issue with wp_inline_script_attributes, because if it is intended for front end, then it shouldn't run in the backend - but does, and misses the array key type in that case. [...] the very least we would need to specify on the doc page that this needs to be hooked explicitly to front end, or that an isset() should be run (which IMO is quite uncommon for filters/hooks, usually they run only where the data is available)

This filter is not specific for the frontend. It is intended to be used in any context, whether frontend or admin. The type array key is only supplied automatically if the page is not HTML5. So yes, an isset() check should always be done for $attributes['type']. If it is not set, then it is assumed to be text/javascript, per the HTML spec.

I also notice that the documentation for the related wp_get_inline_script_tag is wrongly saying to use wp_script_attributes to filter the tags.

Good catch. The phpdoc for wp_get_inline_script_tag() needs to be updated.

#6 @westonruter
15 months ago

  • Description modified (diff)

This ticket was mentioned in ​PR #9416 on ​WordPress/wordpress-develop by ​@debarghyabanerjee.


15 months ago
#7

  • Keywords has-patch added; needs-patch removed

Trac Ticket: Core-63806

This pull request updates all inline script outputs in the bundled themes to use WordPress’s script helper functions, specifically wp_print_inline_script_tag(), in place of manually constructed <script> tags.

---

## ✅ Why This Matters

As of #59446, WordPress Core has adopted the use of wp_get_script_tag(), wp_get_inline_script_tag(), and wp_print_inline_script_tag() to eliminate manually constructed <script> tags. This change was made to:

However, many default and third-party themes still use raw <script> tags, which prevents them from fully benefiting from these improvements.

---

## 🛠 What’s Changed

  • Replaced all instances of echo '<script>...</script>' with calls to wp_print_inline_script_tag().

---

## 🔙 Backward Compatibility
Since these helper functions were introduced in WordPress 5.7+, this PR also includes polyfill definitions in functions.php to ensure compatibility with earlier WordPress versions.

The polyfills conditionally define wp_print_inline_script_tag() and wp_get_inline_script_tag() functions only if they don’t already exist, making it safe for all supported versions.

#8 @jonsurrell
15 months ago

#52497 was marked as a duplicate.

​@westonruter commented on ​PR #9416:


14 months ago
#9

@Debarghya-Banerjee Hello! Have you seen the latest PR feedback yet?

Also, note the comment I just added to the ticket, related the changes to Core-63887.

​@debarghyabanerjee commented on ​PR #9416:


14 months ago
#10

Hi @westonruter , I have checked the comments and feedback, I am working on it, and will push the changes in sometime by today itself. Thanks.

​@debarghyabanerjee commented on ​PR #9416:


14 months ago
#11

Hi @westonruter , Apologies for the late update. I’ve pushed the changes based on your and @sabernhardt 's feedback. Could you please take a look? Thanks!

​@westonruter commented on ​PR #9416:


14 months ago
#12

@Debarghya-Banerjee Are you planning to address the remaining feedback or should we start pushing up commits to this PR? Thanks!

​@debarghyabanerjee commented on ​PR #9416:


14 months ago
#13

Hi @westonruter , I have addressed the feedback. Sorry for getting back late. Can you please check once? Thanks.

​@westonruter commented on ​PR #9416:


13 months ago
#14

I wrote a script that checked the output of rendered output of the homepages for each of the themes to verify that there were no regressions in the generated markup, and that only the expected changes occur:

<details><summary><code>grab-output.sh</code></summary>

#!/bin/bash

outdir=/tmp/trac-63806-output
mkdir -p "$outdir"
echo '' > "$outdir/report.md"

check_theme() {
	theme="$1"
	url="$2"
	theme_dir="/tmp/trac-63806-output/$1"
	echo "# $theme" >> "$outdir/report.md"
	mkdir -p "$theme_dir"
	npm run env:cli theme activate "$theme"
	git checkout trunk
	curl -s "$url" > "$theme_dir/before.html"
	git checkout fix/63806-update-themes-to-use-wp_print_script_tag
	curl -s "$url" > "$theme_dir/after.html"
	prettier "$theme_dir/before.html" > "$theme_dir/before.prettier.html"
	prettier "$theme_dir/after.html" > "$theme_dir/after.prettier.html"
	diff -u "$theme_dir/before.html" "$theme_dir/after.html" > "$theme_dir/raw.diff"
	diff -u "$theme_dir/before.prettier.html" "$theme_dir/after.prettier.html" > "$theme_dir/prettier.diff"

	{
		echo "URL: \`$url\`"
		echo
		echo 'Prettier Diff:'
		echo '{{{diff'
		cat "$theme_dir/prettier.diff"
		echo '}}}'
		echo
		echo '<details><summary>Raw Diff</summary>'
		echo
		echo '{{{diff'
		cat "$theme_dir/raw.diff"
		echo '}}}'
		echo
		echo '</details>'
		echo
	} >> "$outdir/report.md"
}

home_url="http://localhost:8000/?enable_plugins=none"

check_theme twentyfifteen "$home_url"
check_theme twentyseventeen "$home_url"
check_theme twentysixteen "$home_url"
check_theme twentytwenty "$home_url"
check_theme twentytwentyone "$home_url"

cat "$outdir/report.md"

</details>

Here is the output:

# twentyfifteen
URL: http://localhost:8000/?enable_plugins=none

Prettier Diff:

  • /tmp/trac-63806-output/twentyfifteen/

    old new  
    99      (function (html) {
    1010        html.className = html.className.replace(/\bno-js\b/, "js");
    1111      })(document.documentElement);
     12      //# sourceURL=twentyfifteen_javascript_detection
    1213    </script>
    1314    <title>WordPress Develop</title>
    1415    <meta name="robots" content="max-image-preview:large" />

<details><summary>Raw Diff</summary>

  • /tmp/trac-63806-output/twentyfifteen/

    old new  
    55        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    66        <link rel="profile" href="https://gmpg.org/xfn/11">
    77        <link rel="pingback" href="http://localhost:8000/xmlrpc.php">
    8         <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>
     8        <script>
     9(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);
     10//# sourceURL=twentyfifteen_javascript_detection
     11</script>
    912<title>WordPress Develop</title>
    1013<meta name='robots' content='max-image-preview:large' />
    1114<link rel="alternate" type="application/rss+xml" title="WordPress Develop &raquo; Feed" href="http://localhost:8000/feed/" />

</details>

# twentyseventeen
URL: http://localhost:8000/?enable_plugins=none

Prettier Diff:

  • /tmp/trac-63806-output/twentyseventeen/

    old new  
    99      (function (html) {
    1010        html.className = html.className.replace(/\bno-js\b/, "js");
    1111      })(document.documentElement);
     12      //# sourceURL=twentyseventeen_javascript_detection
    1213    </script>
    1314    <title>WordPress Develop</title>
    1415    <meta name="robots" content="max-image-preview:large" />

<details><summary>Raw Diff</summary>

  • /tmp/trac-63806-output/twentyseventeen/

    old new  
    55<meta name="viewport" content="width=device-width, initial-scale=1.0">
    66<link rel="profile" href="https://gmpg.org/xfn/11">
    77
    8 <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>
     8<script>
     9(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);
     10//# sourceURL=twentyseventeen_javascript_detection
     11</script>
    912<title>WordPress Develop</title>
    1013<meta name='robots' content='max-image-preview:large' />
    1114<link rel="alternate" type="application/rss+xml" title="WordPress Develop &raquo; Feed" href="http://localhost:8000/feed/" />

</details>

# twentysixteen
URL: http://localhost:8000/?enable_plugins=none

Prettier Diff:

  • /tmp/trac-63806-output/twentysixteen/

    old new  
    88      (function (html) {
    99        html.className = html.className.replace(/\bno-js\b/, "js");
    1010      })(document.documentElement);
     11      //# sourceURL=twentysixteen_javascript_detection
    1112    </script>
    1213    <title>WordPress Develop</title>
    1314    <meta name="robots" content="max-image-preview:large" />

<details><summary>Raw Diff</summary>

  • /tmp/trac-63806-output/twentysixteen/

    old new  
    44        <meta charset="UTF-8">
    55        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    66        <link rel="profile" href="https://gmpg.org/xfn/11">
    7                 <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>
     7                <script>
     8(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);
     9//# sourceURL=twentysixteen_javascript_detection
     10</script>
    811<title>WordPress Develop</title>
    912<meta name='robots' content='max-image-preview:large' />
    1013<link rel="alternate" type="application/rss+xml" title="WordPress Develop &raquo; Feed" href="http://localhost:8000/feed/" />

</details>

# twentytwenty
URL: http://localhost:8000/?enable_plugins=none

Prettier Diff:

  • /tmp/trac-63806-output/twentytwenty/

    old new  
    618618    <script>
    619619      document.documentElement.className =
    620620        document.documentElement.className.replace("no-js", "js");
     621      //# sourceURL=twentytwenty_no_js_class
    621622    </script>
    622623    <style id="custom-background-css">
    623624      body.custom-background {

<details><summary>Raw Diff</summary>

  • /tmp/trac-63806-output/twentytwenty/

    old new  
    7878<script src="http://localhost:8000/wp-content/themes/twentytwenty/assets/js/index.js?ver=2.9" id="twentytwenty-js-js" defer data-wp-strategy="defer"></script>
    7979<link rel="https://api.w.org/" href="http://localhost:8000/wp-json/" /><link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://localhost:8000/xmlrpc.php?rsd" />
    8080<meta name="generator" content="WordPress 6.9-alpha-60093-src" />
    81         <script>document.documentElement.className = document.documentElement.className.replace( 'no-js', 'js' );</script>
    82         <style id="custom-background-css">
     81<script>
     82document.documentElement.className = document.documentElement.className.replace( 'no-js', 'js' );
     83//# sourceURL=twentytwenty_no_js_class
     84</script>
     85<style id="custom-background-css">
    8386body.custom-background { background-color: #fff; }
    8487</style>

</details>

# twentytwentyone
URL: http://localhost:8000/?enable_plugins=none

Prettier Diff:

  • /tmp/trac-63806-output/twentytwentyone/

    old new  
    15241524    </script>
    15251525    <script>
    15261526      document.body.classList.remove("no-js");
     1527      //# sourceURL=twenty_twenty_one_supports_js
    15271528    </script>
    15281529    <button
    15291530      id="dark-mode-toggler"
    … …  
    16221623
    16231624      darkModeInitialLoad();
    16241625      darkModeRepositionTogglerOnScroll();
     1626      //# sourceURL=http://localhost:8000/wp-content/themes/twentytwentyone/assets/js/dark-mode-toggler.js
    16251627    </script>
    16261628    <script>
    16271629      if (
    … …  
    16301632      ) {
    16311633        document.body.classList.add("is-IE");
    16321634      }
     1635      //# sourceURL=twentytwentyone_add_ie_class
    16331636    </script>
    16341637    <style id="core-block-supports-inline-css">
    16351638      /**

<details><summary>Raw Diff</summary>

  • /tmp/trac-63806-output/twentytwentyone/

    old new  
    470470<script type="speculationrules">
    471471{"prefetch":[{"source":"document","where":{"and":[{"href_matches":"/*"},{"not":{"href_matches":["/wp-*.php","/wp-admin/*","/wp-content/uploads/*","/wp-content/*","/wp-content/plugins/*","/wp-content/themes/twentytwentyone/*","/*\\?(.+)"]}},{"not":{"selector_matches":"a[rel~=\"nofollow\"]"}},{"not":{"selector_matches":".no-prefetch, .no-prefetch a"}}]},"eagerness":"conservative"}]}
    472472</script>
    473 <script>document.body.classList.remove("no-js");</script><button id="dark-mode-toggler" class="fixed-bottom" aria-pressed="false" onClick="toggleDarkMode()">Dark Mode: <span aria-hidden="true"></span></button>               <style>
     473<script>
     474document.body.classList.remove('no-js');
     475//# sourceURL=twenty_twenty_one_supports_js
     476</script>
     477<button id="dark-mode-toggler" class="fixed-bottom" aria-pressed="false" onClick="toggleDarkMode()">Dark Mode: <span aria-hidden="true"></span></button>                <style>
    474478                        #dark-mode-toggler > span {
    475479                                margin-left: 5px;
    476480                        }
    … …  
    482486                        }
    483487                                        </style>
    484488
    485                 <script>function toggleDarkMode() { // jshint ignore:line
     489                <script>
     490function toggleDarkMode() { // jshint ignore:line
    486491        var toggler = document.getElementById( 'dark-mode-toggler' );
    487492
    488493        if ( 'false' === toggler.getAttribute( 'aria-pressed' ) ) {
    … …  
    553558
    554559darkModeInitialLoad();
    555560darkModeRepositionTogglerOnScroll();
    556 </script>       <script>
    557         if ( -1 !== navigator.userAgent.indexOf( 'MSIE' ) || -1 !== navigator.appVersion.indexOf( 'Trident/' ) ) {
    558                 document.body.classList.add( 'is-IE' );
    559         }
    560         </script>
    561         <style id='core-block-supports-inline-css'>
     561//# sourceURL=http://localhost:8000/wp-content/themes/twentytwentyone/assets/js/dark-mode-toggler.js
     562</script>
     563<script>
     564                if ( -1 !== navigator.userAgent.indexOf('MSIE') || -1 !== navigator.appVersion.indexOf('Trident/') ) {
     565                        document.body.classList.add('is-IE');
     566                }
     567        //# sourceURL=twentytwentyone_add_ie_class
     568</script>
     569<style id='core-block-supports-inline-css'>
    562570/**
    563571 * Core styles: block-supports
    564572 */

</details>

#15 @westonruter
13 months ago

In 60913:

Bundled Themes: Use wp_print_inline_script_tag() when available and include sourceURL for JS.

Instead of manually constructing the markup for SCRIPT tags, leverage wp_print_inline_script_tag() when available to do the construction while also ensuring filters may inject additional attributes on the SCRIPT tags, such as nonce for CSP. When the function is not available (prior to WP 5.7), fall back to the manual markup construction.

This also adds the sourceURL comments to the inline scripts to facilitate debugging, per #63887.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/9416.

Follow-up to [60909], [60899].

Props debarghyabanerjee, westonruter, hbhalodia, peterwilsoncc, sabernhardt, poena.
See #63887, #59446.
Fixes #63806.

This ticket was mentioned in ​Slack in #core by jorbin. ​View the logs.


13 months ago

This ticket was mentioned in ​Slack in #core by westonruter. ​View the logs.


12 months ago

#18 @westonruter
4 months ago

In 62723:

Script Loader: Enable attribute filters for concatenated scripts.

Replace the manually constructed <script> markup in _print_scripts() with wp_print_inline_script_tag() and wp_print_script_tag(). The merged inline script holding the concatenated wp_localize_script() data, and the load-scripts.php tag itself, are now passed through the wp_inline_script_attributes and wp_script_attributes filters, as every other script tag in core already is. Themes and plugins can therefore add attributes to them, such as the nonce needed to serve the admin under a Content-Security-Policy that disallows unsafe-inline.

The emitted markup is otherwise unchanged, aside from the attribute quoting and entity encoding applied by WP_HTML_Tag_Processor.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/11702.
Follow-up to r56687, r60719.

Props sukhendu2002, galaxor, wildworks, westonruter.
See #51407, #57548, #58664, #59446.
Fixes #64683.

#19 @thanhtinpk
3 months ago

Hi @westonruter (and committers),

I'd like to help move this ticket forward by taking ownership of a bounded slice.

Proposed slice: migrate the remaining raw <script> blocks in wp-admin/includes/media.php
and wp-admin/admin-header.php to wp_get_inline_script_tag() / wp_print_inline_script_tag(),
matching the patterns established in r60909 and r60913.

Why this slice: every migrated block routes through the wp_inline_script_attributes filter
(script-loader.php:3034 on trunk @ 02778fd6a1), which is the central point a future CSP nonce
will need. That makes this a concrete prerequisite for the report-only CSP rollout discussed on
this ticket, and it is fully verifiable: PHPUnit per touched subsystem plus a before/after
rendered-markup diff (the grab-output.sh approach from PR #9416) showing only expected
<script> attribute changes.

Verification I'll provide with the patch:
PHPUnit coverage for each touched subsystem.

A rendered-output diff proving no functional markup change beyond the added attributes.

Two questions before I start:

Is wp-admin/includes/media.php + admin-header.php the right first slice, or would you prefer a different subsystem first?

Should the per-subsystem migrations be tracked on this ticket, or split into child tickets as the work progresses?

Happy to start as soon as the scope is confirmed.

This ticket was mentioned in ​PR #13319 on ​WordPress/wordpress-develop by ​tinhien11.


3 months ago
#20

## Description

Follows up on the Trac ticket discussion (comment 19): migrates the raw inline
<script> blocks in wp-admin/admin-header.php and wp-admin/includes/media.php to
wp_print_inline_script_tag(), matching the patterns established in r60909 / r60913.

This is a prerequisite slice for the Content Security Policy rollout discussed in Trac #59446:
once all admin inline scripts route through the script tag API, the
wp_inline_script_attributes filter becomes the single point where a per-request nonce can be
attached.

## Changes

  • wp-admin/admin-header.php: the global admin JS (addLoadEvent, ajaxurl, pagenow, typenow, adminpage, locale separators, isRtl) and the no-js -> js body-class replacement are now printed via wp_print_inline_script_tag().
  • wp-admin/includes/media.php: 10 of the 11 inline script blocks (send-to-editor handoff, plupload init, preloaded media item lists, wpOnload() trigger, post_id echo) migrated. The disable_captions conditional and the dynamic admin image URLs keep their existing behavior.
  • Deferred: the addExtImage raw block (the only remaining <script> in media.php) needs the same treatment but ships separately to keep this slice reviewable.

## Verification

  • php -l on both files.
  • The emitted JS is byte-identical to the previous output (same esc_js() values, same statement order; only the surrounding <script> wrapper newlines differ).
  • Rendered-markup diff on a live admin page will be attached from the PR test run.

## Next steps

With this in place, the script-loader can attach a per-request nonce via the
wp_inline_script_attributes filter, enabling the report-only CSP discussed in Trac #59446.

Trac ticket: https://core.trac.wordpress.org/ticket/59446 (see comment 19).

​tinhien11 commented on ​PR #13319:


3 months ago
#21

Thanks for the detailed review @westonruter — all points addressed in cfaa362:

  • Nowdoc everywhere: the admin-header no-js replacement script, the three preloaded handlers in media.php, and the popup addLoadEvent.
  • media-upload-popup globals block now mirrors admin-header: unminified, strict-mode-compatible addLoadEvent, and Object.assign( window, wp_json_encode( ... ) ) with JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS. The popup keeps its original variable subset (ajaxurl, pagenow, adminpage, isRtl).
  • media_send_to_editor() uses the suggested sprintf() + wp_json_encode() form.
  • PHP close/reopen pairs removed: the wp_print_inline_script_tag() calls now sit directly in the surrounding PHP blocks in media_send_to_editor(), wp_iframe() (×2), media_upload_form_handler(), media_upload_gallery_form(), and both spots in admin-header.php.
  • isRtl stays (int) as in your suggestion, preserving the previous JS value type.

Coding standards (PHP/JS) and PHP compatibility pass on the new head; the rest of the matrix is running.

#22 @westonruter
2 months ago

  • Milestone Future Release → 7.2

​@westonruter commented on ​PR #13319:


2 months ago
#23

🤖 _Comment by Claude Opus 5_

Two behavioral changes in this PR are not apparent from the diff and are worth stating explicitly for review, followed by a note on the scope that was added for consistency and what was verified in a browser.

## 1. Replacing esc_js() with wp_json_encode() changes the emitted values

This is not a pure refactor. esc_js() does two things that JSON encoding does not: it runs the value through _wp_specialchars( $text, ENT_COMPAT ), and it applies stripslashes(). The consequence is that the JavaScript string previously contained HTML entities rather than the literal characters:

Input Before (esc_js inside '…') After (wp_json_encode)
Tom & Jerry 'Tom &amp; Jerry' "Tom & Jerry"
a "quoted" value 'a &quot;quoted&quot; value' "a \"quoted\" value"
back\slash 'back\slash' (backslash lost) "back\\slash"
&nbsp; '&amp;nbsp;' "&nbsp;"

Every case above is a correction rather than a regression, since the old output was mangled. The affected values are ajaxurl, pagenow, typenow, adminpage, thousandsSeparator and decimalPoint. The two locale-supplied separators are the ones most likely to contain an affected character in practice, as they come from translations.

## 2. The js_escape filter no longer runs for these values

esc_js() ends with apply_filters( 'js_escape', $safe_text, $text ). Any plugin hooking that filter was previously able to alter the six values listed above. That extension point is gone for them. It is an obscure surface, but it is a removal rather than a change.

## 3. Global property descriptors are no longer identical to before

Because var ajaxurl = … became Object.assign( window, … ), and addLoadEvent = function … became a function declaration, the resulting global properties carry different descriptors. This was measured in a browser rather than inferred:

Global Before After
ajaxurl, pagenow, typenow, adminpage configurable: false configurable: true
addLoadEvent configurable: true configurable: false

The flags move in opposite directions because the old globals were created by var (non-configurable) while addLoadEvent was an implicit global assignment (configurable). Values, writability and enumerability are unchanged, and isRtl remains a number. The practical effect is that delete window.ajaxurl now succeeds where it previously could not. No core or bundled code depends on either behavior.

## Scope added for consistency

The same block of global admin JavaScript existed in three places. Only two were covered initially, which would have left Thickbox iframes on the old esc_js() behavior while every other admin screen used the new one — so a thousands_sep containing an ampersand would have arrived as &amp; in an iframe and as & elsewhere. iframe_header() and iframe_footer() in wp-admin/includes/template.php have therefore been migrated as well, which also brings tb_close() across.

iframe_footer() matters most of the three: it holds the script that actually invokes wpOnload, so leaving it as a raw tag would have caused every callback registered through addLoadEvent() on a Thickbox iframe to be silently dropped under a CSP while the surrounding page continued to work.

compression_test() in the same file still emits a raw <script> and has deliberately been left alone, as its removal is intended separately.

## Deliberately not changed

wp_json_encode() can return false, in which case sprintf( 'Object.assign( window, %s );', false ) emits a syntax error. Guarding this was considered and rejected: a filter that renders the data non-encodable is a bug, and a loud SyntaxError surfaces it better than a silent fallback would. The realistic path to false is narrow in any case, since wp_json_encode() retries through _wp_json_sanity_check(), which strips invalid UTF-8.

The JSON flags were also narrowed to JSON_HEX_TAG | JSON_UNESCAPED_SLASHES throughout. JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_LINE_TERMINATORS are only safe when the page is served as UTF-8, which is not guaranteed in the admin, as admin-header.php sends the charset straight from the blog_charset option. WP_Script_Modules::print_script_module_data() gates the same pair behind is_utf8_charset() for this reason. Rather than repeat that gate at several call sites for a marginal saving on very small payloads, the narrower pair is now used everywhere, matching the rest of core.

## Verification

Checked in a browser against the running admin:

  • All globals carry their expected values and types on the Dashboard, on media-upload.php in both the type and type_url tabs, and on a Thickbox iframe page.
  • wpOnload() is invoked exactly once from iframe_footer(), and the tag remains positioned after the closing div that wraps the footer hooks.
  • The addExtImage block survives WP_HTML_Tag_Processor byte-for-byte, including '</a>', replace(/</g, '&lt;') and '<br />', with none of the Unicode escaping that escape_javascript_script_contents() would apply to a <script or </script sequence. It was then driven through its real inline handlers: the onblur populated width and height from an actual image, the align radio's onclick set addExtImage.align, and insert() produced the expected caption shortcode.
  • plupload initializes and window.uploader is instantiated.
  • tb_close() resolves the same target and preserves this.
  • No console errors on any page. The only console output anywhere was a pre-existing JQMIGRATE deprecation notice and a pre-existing <label for> issue, neither touched here.

The "Insert media from another website" tab is still not usable under a strict CSP even with its script tag now able to carry a nonce, because wp_media_insert_url_form() drives addExtImage entirely through inline onclick and onblur attributes, which a nonce cannot cover. That needs a separate change.

#24 @thanhtinpk
2 months ago

Following the 7.2 milestone — I'd like to take the follow-up noted in the review of GitHub PR 13319 (​https://github.com/WordPress/wordpress-develop/pull/13319): the "Insert media from another website" tab is still unusable under a strict CSP because wp_media_insert_url_form() drives addExtImage through inline onclick/onblur attributes, which a nonce cannot cover. I have a patch ready that binds the same handlers from the existing nonce-eligible script block on DOMContentLoaded, and will open the PR on top of it as soon as it lands.

This ticket was mentioned in ​PR #13393 on ​WordPress/wordpress-develop by ​@thanhtinpk.


2 months ago
#25

## Description

Follows up on the inline script migration in #13319 for the Content Security Policy rollout discussed in Trac #59446: wraps the remaining one-liner raw <script> tags in wp_print_inline_script_tag(), so every script these pages print can carry a per-request nonce.

Under a CSP that only allows nonce'd scripts, each raw tag replaced here was blocked outright: the wpOnload() trigger on every admin screen, the installer's title focus, and the upload-error dismissal.

## Changes

### wp-admin/admin-footer.php

  • The wpOnload() trigger printed at the end of every admin screen now goes through wp_print_inline_script_tag(), mirroring the iframe_footer() migration in #13319.

### wp-admin/install.php

  • The installer's weblog_title focus helper (non-mobile) and the hide-if-no-js class-removal block are wrapped the same way. The needless PHP close/reopen pair between them is removed.

### wp-admin/async-upload.php

  • The upload-error speak-and-dismiss handler is printed via wp_print_inline_script_tag() instead of a manually assembled echo '<script>…'. The dismiss button selector is passed through wp_json_encode() as one whole string, replacing raw string interpolation of the id.

## Behavioral notes

  • The emitted JavaScript is semantically identical; only the formatting of the wpOnload and installer blocks is normalized.
  • wp_print_inline_script_tag() appends a trailing newline after the closing tag, matching the raw echo it replaces in async-upload.php.
  • Hardening aside, the dismiss selector construction now can never break on unusual ids, since the full button#… string is JSON-encoded rather than the id being interpolated inside quotes.

## Verification

  • php -l on all three files.
  • The four emitted script bodies were executed against a simulated DOM: wpOnload guard (no-op when undefined, invoked when defined), installer focus, .hide-if-no-js removal on ready, and the full dismiss chain (click → parents( 'div.media-item' ) → slideUp → remove → wp.a11y.speak).
  • Emitted tags were validated through the real wp_get_inline_script_tag() implementation, including its unsafe-content guard for </script> sequences.

compression_test() in wp-admin/includes/template.php intentionally remains untouched, per #13319.

#26 @westonruter
2 months ago

In 63481:

Administration: Use wp_print_inline_script_tag() in more places.

Continuing the migration away from manually constructed SCRIPT markup, a subset of the admin's raw inline scripts now print through wp_print_inline_script_tag(): those in wp-admin/admin-header.php, those in wp-admin/includes/media.php, and those in iframe_header()/iframe_footer() in wp-admin/includes/template.php. For those screens this is what r56687 did for the frontend and the login screen, making wp_inline_script_attributes the single point at which a per-request nonce can be attached. This is one step toward an admin Content Security Policy opt-in rather than the whole of it.

The data these scripts carry is now serialized with wp_json_encode() using JSON_HEX_TAG | JSON_UNESCAPED_SLASHES instead of being assembled from esc_js() string fragments. This corrects the values that reach JavaScript: esc_js() passes the text through _wp_specialchars(), so ajaxurl, pagenow, typenow, adminpage, thousandsSeparator, and decimalPoint previously arrived carrying HTML entities in place of the literal characters (e.g. a thousands_sep of & was delivered as &amp;).

Inlined JS is also unminified and reformatted, with improvements to strict-mode compatibility. Static blocks use nowdoc heredocs so that editors syntax-check the JavaScript.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/13319.
Follow-up to r56687, r60681, r60909, r60913.

Props thanhtinpk, westonruter.
See #59444, #59446, #63851.

​@westonruter commented on ​PR #13393:


2 months ago
#27

Please add the AI Disclosure section from the PR template to indicate whether/how AI was used in the construction of this PR.

#28 @westonruter
2 months ago

In 63545:

Administration: Wrap more one-liner inline scripts.

Continuing the migration begun in r63481, the raw one-liner SCRIPT tags in wp-admin/admin-footer.php, wp-admin/install.php and wp-admin/async-upload.php now print through wp_print_inline_script_tag(), so wp_inline_script_attributes can attach a per-request nonce to these as well.

The upload error handler is reworked in the process:

  1. Its data now crosses into JavaScript as a single wp_json_encode() object rather than being interpolated into the script text, which also removes the raw interpolation of the dismiss button's generated id.
  2. The jQuery object arrives as an argument instead of being read from the global scope four times.
  3. setTimeout() replaces the lone _.delay() call, which was all the snippet wanted from Underscore.

The two blocks that take an argument carry a JSDoc block naming its type, following the convention already used for the jQuery wrapper in wp-admin/js. These particular blocks are not reached by lint:jsdoc, which reads JavaScript files rather than heredocs embedded in PHP, but IDEs do check them.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/13393.
Follow-up to r60263, r60520, r60681, r63481.

Props thanhtinpk, westonruter.
See #59446, #66033.

#29 follow-up: @TobiasBg
2 months ago

In quite a few places, this now sends JSDoc to the browser, adding extra bytes to the requests. Wouldn't it be sufficient to have have these in the PHP code only?

#30 in reply to: ↑ 29 @westonruter
2 months ago

Replying to TobiasBg:

In quite a few places, this now sends JSDoc to the browser, adding extra bytes to the requests. Wouldn't it be sufficient to have have these in the PHP code only?

We should really be moving all such scripts into JS files which get read in via file_get_contents() (as is done for the emoji loader via print_emoji_detection_script()), and in this way the build process can generate the minified versions which we can then inline serve when SCRIPT_DEBUG is turned off. I hinted at that in my ​PR comment, but it was out of scope for that changeset.

#31 @westonruter
2 months ago

A couple notes for getting this to the finish line:

Not all existing <script> tags will be suitable for directly being replaced with wp_print_inline_script_tag(). In some cases, existing <script> tags should be wrapped in ob_start() and ob_get_clean() with the return value of the latter being passed through wp_remove_surrounding_empty_script_tags() which is then passed into wp_print_inline_script_tag(). An example of this is in media_upload_type_url_form() where there are PHP conditionals inline with the JS code that make it more difficult to extract into a NOWDOC. (That said, it would still be ideal to get rid of this, but probably later as part of another effort.)

Non-JS SCRIPT tags will need to be converted as well. Before the TEMPLATE tag existed, core used the SCRIPT tag with a non-JS type. For example, wp_print_community_events_templates() includes this:

        <script id="tmpl-community-events-attend-event-near" type="text/template">
                <?php
                printf(
                        /* translators: %s: The name of a city. */
                        __( 'Attend an upcoming event near %s.' ),
                        '<strong>{{ data.location.description }}</strong>'
                );
                ?>
        </script>

This doesn't need any NOWDOC at all. It can simply switch to using sprintf():

<?php
wp_print_inline_script_tag(
        sprintf(
                /* translators: %s: The name of a city. */
                __( 'Attend an upcoming event near %s.' ),
                '<strong>{{ data.location.description }}</strong>'
        ),
        array(
                'id'   => 'tmpl-community-events-attend-event-near',
                'type' => 'text/template',
        )
);

For more complicated HTML templates with nested PHP conditionals where wp_remove_surrounding_empty_script_tags() is needed, it will need to be modified to allow not warn when attributes are included on the <script> tag, so that this can be done (but not with this specific example):

<?php ob_start(); ?>
<script id="tmpl-community-events-attend-event-near" type="text/template">
        <?php
        printf(
                /* translators: %s: The name of a city. */
                __( 'Attend an upcoming event near %s.' ),
                '<strong>{{ data.location.description }}</strong>'
        );
        ?>
</script>
<?php
wp_print_inline_script_tag(
        wp_remove_surrounding_empty_script_tags( ob_get_clean() ),
        array(
                'id'   => 'tmpl-community-events-attend-event-near',
                'type' => 'text/template',
        )
);
?>

For example, wp_remove_surrounding_empty_script_tags() could be modified as follows:

<?php
function wp_remove_surrounding_empty_script_tags( $contents ) {
        $contents = trim( $contents );

        $processor = new WP_HTML_Tag_Processor( $contents );
        if ( ! $processor->next_tag( 'SCRIPT' ) ) { // TODO: Use next_token() and also verify that '</script>' is the last token.
                $error_message = __( 'Expected string to start with script tag and end with script tag, with optional whitespace.' );
                _doing_it_wrong( __FUNCTION__, $error_message, '7.2' );
                return sprintf(
                        'console.error(%s)',
                        wp_json_encode(
                                sprintf(
                                        /* translators: %s: wp_remove_surrounding_empty_script_tags() */
                                        __( 'Function %s used incorrectly in PHP.' ),
                                        'wp_remove_surrounding_empty_script_tags()'
                                ) . ' ' . $error_message
                        )
                );
        }

        return $processor->get_modifiable_text();
}

(Note the TODO comment to make this more robust.)

That said, it would be even better if we could avoid relying on wp_remove_surrounding_empty_script_tags() entirely, as well as moving all of these inline JS snippets to external files which can be included with file_get_contents() per my preceding comment.

#32 @westonruter
2 months ago

  • Keywords needs-patch added; has-patch removed

This ticket was mentioned in ​PR #13492 on ​WordPress/wordpress-develop by ​@haritpanchal.


2 months ago
#33

  • Keywords has-patch added; needs-patch removed

Continues the migration away from manually constructed SCRIPT markup begun in [63481] and [63545]. The four raw one-liner script tags in Bulk_Upgrader_Skin::error(), ::before(), and ::after() now print through wp_print_inline_script_tag(), so wp_inline_script_attributes can attach a per-request nonce to these as well — one more step toward an admin Content-Security-Policy opt-in.

The dynamic jQuery selector is now passed through wp_json_encode() with JSON_HEX_TAG | JSON_UNESCAPED_SLASHES instead of being built via esc_js() string concatenation, consistent with the fix applied to similar call sites in [63481]: esc_js() runs the value through _wp_specialchars(), which isn't needed here since the value lands inside a JS string literal, not an HTML attribute.

Behavior is unchanged — output was compared before/after with a manual smoke test of all three methods.

## Testing instructions

  1. Go to Plugins → Add New, install/update a plugin, or use Dashboard → Updates to bulk-update plugins/themes.
  2. Confirm the spinner and progress states still toggle correctly during and after the bulk update.
  3. npm run test:php -- --group upgrade passes (183 tests).
  4. vendor/bin/phpcs --standard=phpcs.xml.dist src/wp-admin/includes/class-bulk-upgrader-skin.php is clean.

Trac ticket: https://core.trac.wordpress.org/ticket/59446

## Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Sonnet 5
Used for: Identifying the unconverted call sites, drafting the wp_print_inline_script_tag() replacement, and running the coding-standards/PHPUnit/manual smoke checks. I reviewed the diff and test output before opening this PR.

#34 @haritpanchal
2 months ago

Opened a PR continuing the migration from [63481]/[63545]: ​https://github.com/WordPress/wordpress-develop/pull/13492

Bulk_Upgrader_Skin had four raw one-liner <script> tags (in error(), before(), and after()) that hadn't been converted yet. They now go through wp_print_inline_script_tag(), with the dynamic selector passed via wp_json_encode() instead of esc_js() concatenation, matching the approach used elsewhere in this ticket.

Verified with npm run test:php -- --group upgrade (183/183 passing), phpcs against phpcs.xml.dist (clean), and a manual smoke test of all three methods to confirm identical script output before/after.

Happy to take this further if there are other files in scope that should go in the same PR, or keep it split out — let me know what's preferred.

This ticket was mentioned in ​PR #13646 on ​WordPress/wordpress-develop by ​sjackson0109.


8 weeks ago
#35

  • Keywords has-unit-tests added

Description

Continues the inline script migration for the Content Security Policy rollout discussed in Trac #59446.

WP_List_Table::_js_vars() and the WP_Themes_List_Table override each printed a raw one-liner <script> tag built with printf(). Under a CSP that only allows nonce'd scripts, both were blocked outright: raw markup cannot receive attributes through wp_inline_script_attributes.

Both call sites now print through wp_print_inline_script_tag(), so a per-request nonce (or any other attribute) added via wp_inline_script_attributes is attached to the emitted tag.

The base WP_List_Table::_js_vars() fix covers every list table screen that does not override the method (Posts, Users, Comments, Plugins, and so on), since WP_Themes_List_Table::_js_vars() and WP_Theme_Install_List_Table::_js_vars() both call parent::_js_vars().

The emitted JavaScript is unchanged; only the tag construction differs.

Testing instructions

  1. Start the WordPress Core development environment.
  2. Apply a nonce through wp_inline_script_attributes.
  3. Enforce a CSP without unsafe-inline on script-src-attr.
  4. Open any admin list table screen (for example Posts, Users, or Themes).
  5. Confirm the list_args/theme_list_args script now carries the nonce.
  6. Confirm the affected admin behaviour (bulk actions, screen options JS, and so on) still works.
  7. Confirm the previous CSP violation for this script is no longer emitted.

Automated checks:

  • php -l on both changed source files: passed.
  • vendor/bin/phpcs against phpcs.xml.dist: 0 errors introduced.
  • npm run test:php (Tests_Admin_WpListTable): 74 tests, 121 assertions, all passing, including two new tests asserting that a nonce added via wp_inline_script_attributes is present in the printed tag.
  • wp eval-file smoke test against the running dev site confirmed the live output changes from a bare <script> tag to <script nonce="..."> for both WP_List_Table and WP_Themes_List_Table.

AI assistance

AI assistance: Yes
Tool(s): Claude Code
Used for: Repository analysis, implementation support and test execution. All changes were reviewed and submitted by Simon Jackson.

​sjackson0109 commented on ​PR #13646:


8 weeks ago
#36

Thanks for the review. Pushed a follow-up commit applying all four points:

  • Added var to the list_args assignment in WP_List_Table::_js_vars() for strict-mode compatibility, matching the existing var theme_list_args declaration in the WP_Themes_List_Table override.
  • Switched to WP_Themes_List_Table::class instead of the string class name in the test.
  • Dropped the remove_filter() calls in both new tests since WP_UnitTestCase already resets hooks between tests.
  • Replaced the substring assertions with WP_HTML_Tag_Processor: locate the SCRIPT tag, then read its nonce attribute and modifiable text directly. I adapted the tag name to SCRIPT rather than TABLE, since _js_vars() only ever prints a script tag.

npm run test:php (Tests_Admin_WpListTable) still passes: 74 tests, 123 assertions.

This ticket was mentioned in ​PR #13653 on ​WordPress/wordpress-develop by ​sjackson0109.


8 weeks ago
#37

Description

Continues the inline script migration for the Content Security Policy rollout discussed in Trac #59446.

WP_Upgrader_Skin::decrement_update_count() printed one of two raw one-liner <script> tags, with the update type concatenated directly into the JavaScript string. Under a CSP that only allows nonce'd scripts, both variants were blocked outright: raw markup cannot receive attributes through wp_inline_script_attributes.

Both variants now print through wp_print_inline_script_tag(), so a per-request nonce (or any other attribute) added via wp_inline_script_attributes is attached to the emitted tag. The update type is now passed through wp_json_encode() rather than being concatenated directly into the script body, matching the convention already used for the sibling Bulk_Upgrader_Skin class in #13492.

This method is inherited by Plugin_Upgrader_Skin, Theme_Upgrader_Skin, Bulk_Plugin_Upgrader_Skin, Bulk_Theme_Upgrader_Skin and Language_Pack_Upgrader_Skin, none of which override it, so the fix covers every plugin, theme and translation update screen that calls it.

The emitted JavaScript is unchanged; only the tag construction and the encoding of the update type differ.

Testing instructions

  1. Start the WordPress Core development environment.
  2. Apply a nonce through wp_inline_script_attributes.
  3. Enforce a CSP without unsafe-inline on script-src-attr.
  4. Update a plugin or theme (or run a bulk update) from wp-admin.
  5. Confirm the printed script carries the nonce.
  6. Confirm the update count in the admin menu still decrements as expected.
  7. Confirm the previous CSP violation for this script is no longer emitted.

Automated checks:

  • php -l on the changed source file: passed.
  • vendor/bin/phpcs against phpcs.xml.dist: 0 errors, 0 warnings.
  • npm run test:php (new file Tests_Admin_WpUpgraderSkin): 5 tests, 10 assertions, all passing, covering the early-return guard, the default branch's nonce attribute, and the IFRAME_REQUEST postMessage branch's nonce attribute.

AI assistance

AI assistance: Yes
Tool(s): Claude Code
Used for: Repository analysis, implementation support and test execution. All changes were reviewed and submitted by Simon Jackson.

​sjackson0109 commented on ​PR #13653:


8 weeks ago
#38

Hello @westonruter, given your involvement in #13646 as a reviewer, please can I request you also review this item.
Both fixes are relating to the exact same CSP nonce-problem
​https://lists.wordpress.org/pipermail/wp-trac/2025-October/550812.html
Given your prior involvement in the email thread, i feel you are likely a good person to offer a constructive review.
Thanks,
Si

​sjackson0109 commented on ​PR #13653:


8 weeks ago
#39

Thanks for the detailed suggestion. Pushed a follow-up commit applying it:

  • Both branches now define their JavaScript as a self-contained arrow function via a nowdoc (with the language=JavaScript marker for editor highlighting), invoked immediately with the JSON-encoded update type passed as a call argument, rather than splicing the encoded value into the middle of the script body.
  • The data provider in the test now has a return type and the suggested PHPStan array-shape @return tag, and the assertions were updated to match the new output shape.

One note: the IFRAME_REQUEST branch also drops the "window.postMessage && JSON" feature-detection guard, per your comment that both are now universally supported. I want to flag that explicitly: this is a behaviour change that the CSP nonce migration itself does not require, so I have made it specifically because you asked for it as part of this patch, not as something I decided was in scope on my own.

npm run test:php (Tests_Admin_WpUpgraderSkin) passes: 5 tests, 13 assertions.

​sjackson0109 commented on ​PR #13653:


8 weeks ago
#40

Good catch, pushed a fix: dropped the redundant PhpStorm workaround comment on the second nowdoc and renamed its label to JS to match your original suggestion. No behaviour change.

​@westonruter commented on ​PR #13646:


8 weeks ago
#41

@sjackson0109 Please link your GitHub account per ​https://github.com/WordPress/wordpress-develop/pull/13646#issuecomment-5779791936

I'll presume that this is your profile: ​https://profiles.wordpress.org/sjackson0109/

#42 @westonruter
8 weeks ago

In 63878:

Administration: Use script helper for list table JS vars.

Print the inline scripts in WP_List_Table::_js_vars() and WP_Themes_List_Table::_js_vars() via wp_print_inline_script_tag() instead of manually constructing SCRIPT tags with printf(). This allows attributes to be added via the wp_inline_script_attributes filter, such as a nonce needed to opt in to a Strict Content Security Policy. This affects the Comments screen, the Activity dashboard widget, and the Comments meta box on the post edit screen. The list_args global is now also declared with var so that the assignment remains valid in strict mode.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/13646.
Follow-up to r56687, r63481, r63545.

Props sjackson0109, westonruter.
See #59446.

​sjackson0109 commented on ​PR #13646:


8 weeks ago
#43

That is one of my Wordpress.org profiles. Except I cannot login/reset that specific profile. My other is ‘VCNS tech’. Happy to use that.On 22 Sep 2026, at 23:03, Weston Ruter *@*.*> wrote:westonruter left a comment (WordPress/wordpress-develop#13646)
@sjackson0109 Please link your GitHub account per #13646 (comment)
I'll presume that this is your profile: ​https://profiles.wordpress.org/sjackson0109/

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: *@*.*>

​@westonruter commented on ​PR #13646:


8 weeks ago
#44

OK, if you can't access sjackson0109 anymore, then please ​connect vcnstech with your GitHub account going forward. Otherwise, please reach out to someone, perhaps in the #meta channel in WordPress Slack to get access again.

#45 @westonruter
8 weeks ago

In 63902:

Administration: Use script helper for update count JS.

Both variants of the inline script printed by WP_Upgrader_Skin::decrement_update_count() now go through wp_print_inline_script_tag() instead of raw SCRIPT markup, so wp_inline_script_attributes can attach a per-request nonce to them. This covers the plugin, theme, and translation update screens, including the bulk updates run in an iframe when IFRAME_REQUEST is defined.

The update type is now passed to the script as a wp_json_encode() argument using JSON_HEX_TAG | JSON_UNESCAPED_SLASHES rather than being concatenated into the JavaScript string. The obsolete window.postMessage && JSON feature check in the iframe variant is removed, as both are universally supported.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/13653.
Follow-up to r27280, r29357, r57148, r63481.

Props sjackson0109, westonruter.
See #59446, #59444.

​sjackson0109 commented on ​PR #13646:


8 weeks ago
#46

Lets keep this tag @westonruter - I prefer to use @sjackson0109.

I'll see if i can close down my work one.

#47 @westonruter
7 weeks ago

In 63947:

Administration: Use script helper for bulk update JS.

The four raw inline SCRIPT tags in Bulk_Upgrader_Skin::error(), ::before(), and ::after(), which toggle the spinner and progress messages during bulk plugin and theme updates, now print through wp_print_inline_script_tag(), so wp_inline_script_attributes can attach a per-request nonce to them.

The selector is now passed to each script as a wp_json_encode() argument using JSON_HEX_TAG | JSON_UNESCAPED_SLASHES rather than being concatenated into the JavaScript string with esc_js(). Each function body is a nowdoc heredoc so that editors can syntax-check the JavaScript.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/13492.
Follow-up to r56687, r63481, r63545, r63902.

Props haritpanchal, westonruter.
See #59446, #59444.

​@sjackson0109 commented on ​PR #13646:


7 weeks ago
#48

I have access to both now - tag either, i don't mind which.

​@westonruter commented on ​PR #13646:


7 weeks ago
#49

Cool. Just please ​connect your accounts to streamline this in the future.

#50 @westonruter
6 weeks ago

  • Owner set to westonruter
  • Status new → accepted

This ticket was mentioned in ​PR #14767 on ​WordPress/wordpress-develop by ​aeonframework.


4 weeks ago
#51

The image editor markup printed by wp_image_editor() binds every control with an inline on* attribute: 48 handlers covering crop, scale, rotate and flip, the popup menu keyboard navigation, undo and redo, save and cancel, the help toggles, the numeric crop and selection fields, and the preview image's onload. The "Edit Image" buttons printed by edit_form_image_editor() and get_media_item() open the editor with an inline onclick too.

A site that sends a nonce-based Content Security Policy without 'unsafe-inline' blocks all of these (script-src-attr). Core already supports adding nonces to every script it prints, through wp_script_attributes and wp_inline_script_attributes. Inline event handlers cannot carry a nonce, though. As a result:

  • On Media > Edit (post.php?post=ID&action=edit), "Edit Image" does nothing.
  • With &image-editor, the editor is printed with the page, but the crop tool never initializes because the preview's onload is blocked.

The image editor is the largest single group of inline handlers left in wp-admin. It had 48 of the 83 on*= attributes in wp-admin/ and wp-includes/ PHP at this base.

Changes

  • wp-admin/includes/image-edit.php: every inline handler is replaced by a data-imgedit-action attribute (buttons), a data-imgedit-input attribute (numeric fields) or a data-imgedit-preview attribute (preview image). A data-imgedit-value attribute carries an argument where one is needed (rotation angle, flip axis, scale/restore, ratio axis). .imgedit-wrap gets data-postid. The nonce is read from the existing #imgedit-nonce-{id} field, so it is no longer interpolated into JavaScript inside HTML attributes.
  • wp-admin/includes/media.php: both "Edit Image" buttons get data-imgedit-open, data-postid and data-nonce.
  • js/_enqueues/lib/image-edit.js: delegated listeners on document call the same imageEdit methods with the same arguments as before:
    • clicks on [data-imgedit-open] and .imgedit-wrap [data-imgedit-action];
    • keydown/blur on the rotate menu;
    • keyup blur on [data-imgedit-input].
  • The preview image's load event does not bubble, so it is caught in the capture phase. A check on DOM ready catches a preview that finished loading before the footer script ran. The attribute is removed when the image is handled, so imgLoaded() runs exactly once either way. The images that refreshEditor() builds are unaffected.
  • The imageEdit method signatures, element IDs and markup structure are unchanged. Code that triggers clicks on these elements keeps working because the listeners are delegated.

Testing

  • New tests/phpunit/tests/admin/includesImageEdit.php, 3 tests:
    • wp_image_editor() and edit_form_image_editor() output has no on* attribute (checked with WP_HTML_Tag_Processor);
    • every control exposes its action, the wrapper's data-postid matches the attachment, and the nonce fields verify for image_editor-{id}.

Before the change all 3 tests fail. After it, vendor/bin/phpunit tests/phpunit/tests/admin/includesImageEdit.php reports OK (3 tests, 26 assertions).

  • Full PHPUnit suite, vendor/bin/phpunit against MySQL 8.0 on PHP 8.3:
    • before: 30761 tests, 28 failures;
    • after: 30764 tests, the same 28 failures;
    • in both runs the failures are in Tests_Template (23), Tests_Dependencies_jQuery (4) and Tests_Script_Modules_WpScriptModules (1), and they come from the environment (the src/ tree was not built).
  • vendor/bin/phpcs on the changed PHP files: no new warnings. The 3 existing warnings in media.php are unchanged.
  • JSHint 2.13.6 with the repo's .jshintrc on image-edit.js: nothing new. The only 2 warnings are the existing == at line 1035.
  • Browser check: headless Chromium against a 7.2-beta1 nightly with the three changed files copied in, SCRIPT_DEBUG on, CONCATENATE_SCRIPTS off. A mu-plugin sends Content-Security-Policy: script-src 'self' 'nonce-…' and adds the nonce through wp_script_attributes and wp_inline_script_attributes.
    • Before: "Edit Image" is blocked (script-src-attr) and the editor never opens. With &image-editor the crop tool never initializes. Three script-src-attr violations came from the editor.
    • After: all of these work, with 0 violations from the image editor:
      • open over Ajax; crop initialized;
      • rotate menu, including ArrowDown to move focus;
      • rotate 90° left, which adds a history step and enables Save;
      • undo and redo;
      • scale width 100, which updates the height (480 → 75);
      • help toggle;
      • Save ("Image saved");
      • server-rendered &image-editor: crop initialized, Cancel closes.
    • The violations still left on that screen come from code outside this patch: the raw <script> tags in wp-admin/includes/misc.php (_wpColorScheme, wp_admin_canonical_url(), the back-forward cache reload) and the TinyMCE init in class-wp-editor.php.

Follow-ups (not in this PR)

  • misc.php's three admin-head scripts go through wp_print_inline_script_tag(), the same pattern as r63545.
  • The remaining inline handlers in the legacy media-upload.php screens (get_media_item() Delete/Cancel and WPSetAsThumbnail, and the addExtImage form), in meta-boxes.php and in the list tables.

Use of AI Tools

AI assistance: Yes
Tool(s): MiniAeon (omp agent harness)
Model(s): Claude Opus 5.5
Used for: finding the remaining inline handlers, drafting the markup and listener changes, the PHPUnit tests and the headless-browser CSP check. The tests and the headless-browser CSP check listed above were run during that work, and the full diff was reviewed by a person before this PR was opened.

​aaronjmars commented on ​PR #14767:


9 days ago
#52

Hi, checking whether this PR needs anything else from me. Happy to address feedback.

#53 @westonruter
4 days ago

  • Milestone 7.2 → 7.3

We're getting close to RC. Let's pick this up again to continue in 7.3.

Note: See TracTickets for help on using tickets.