
內容簡介
**總結:**
- 這個外掛在前端和登入頁面強制執行嚴格的內容安全政策(CSP),以幫助減輕跨站腳本(XSS)漏洞。
- 在#58664中,從WP_Scripts和前端/登入頁面的內聯腳本中消除了手動構建腳本標籤,這要歸功於先前在#39941中引入的輔助函數。
- 使用相關 WordPress API 添加腳本,包括 wp_enqueue_script()、wp_add_inline_script()、wp_localize_script()、wp_print_script_tag()、wp_print_inline_script_tag() 和 wp_enqueue_script_module 以執行腳本。
- 阻止事件處理程序屬性中的腳本,例如 onclick、onchange、onsubmit 和 onload。
- 這個外掛確保從嵌入內容(例如 Twitter 引用)添加到頁面的腳本也會增加 nonce 屬性。
**問題與答案:**
<ul>
<li>這個外掛的作用是什麼?
<ul>
<li>強制執行嚴格的內容安全政策(CSP),以幫助減輕跨站腳本(XSS)漏洞。</li>
</ul>
</li>
<li>在#58664中,從哪裡消除了手動構建腳本標籤?
<ul>
<li>從WP_Scripts和前端/登入頁面的內聯腳本中消除了手動構建腳本標籤,這要歸功於在#39941中引入的輔助函數。</li>
</ul>
</li>
<li>使用哪些 WordPress API 可以添加腳本?
<ul>
<li>使用 wp_enqueue_script()、wp_add_inline_script()、wp_localize_script()、wp_print_script_tag()、wp_print_inline_script_tag() 和 wp_enqueue_script_module。</li>
</ul>
</li>
<li>為什麼阻止事件處理程序屬性中的腳本?
<ul>
<li>因為例如 onclick、onchange、onsubmit 和 onload 中的腳本可能會被阻止。</li>
</ul>
</li>
<li>這個外掛如何處理從嵌入內容(例如 Twitter 引用)添加到頁面的腳本?
<ul>
<li>確保腳本也會增加 nonce 屬性。</li>
</ul>
</li>
</ul>
外掛標籤
開發者團隊
原文外掛簡介
This plugin enforces a Strict Content Security Policy (CSP) on the frontend and login screen. This helps mitigate cross-site scripting (XSS) vulnerabilities. The policy cannot yet be applied to the WP Admin (see #59446).
In #58664, the manual construction of script tags was eliminated from WP_Scripts and inline scripts on frontend/login screen, thanks to the helper functions which had previously been introduced in #39941. This made it possible to apply Strict CSP, as long as themes and plugins are not directly printing '; // ❌
}
add_action( 'wp_footer', 'my_theme_supports_js' );
Instead, do this:
function my_theme_supports_js() {
wp_print_inline_script_tag( 'document.body.classList.remove("no-js");' ); // ✅
}
add_action( 'wp_footer', 'my_theme_supports_js' );
So in order for scripts to execute, they must be printed using the relevant APIs in WordPress for adding scripts, including wp_enqueue_script(), wp_add_inline_script(), wp_localize_script(), wp_print_script_tag(), wp_print_inline_script_tag(), and wp_enqueue_script_module(). Otherwise, a script’s execution will be blocked and an error will appear in the console, for example:
Refused to execute inline script because it violates the following Content Security Policy directive: “script-src ‘nonce-9b539cfe47’ ‘unsafe-inline’ ‘strict-dynamic’ https: http:”. Note that ‘unsafe-inline’ is ignored if either a hash or nonce value is present in the source list.
This also blocks scripts inside of event handler attributes, such as onclick, onchange, onsubmit, and onload. As noted on MDN:
Warning: The use of event handler content attributes is discouraged. The mix of HTML and JavaScript often produces unmaintainable code, and the execution of event handler attributes may also be blocked by content security policies.
This plugin also ensures that scripts added to the page from embeds (e.g. Tweets) also get the nonce attribute added.
