Skip to content

Commit ef999c5

Browse files
draganescuadamziel
andauthored
Fix error from adding blank target to external links (#2575)
## Motivation for the change, related issues We use playground as a preview tool inside an app that generates WordPress blocks via AI assistant. We encounter `JavaScript Error: TypeError: e.target.closest is not a function` coming from Playground and it encumbers our assisted error recovery because it comes from outside of the generated code. ## Implementation details We don't attempt to update the link if the element surprisingly doesn't have a closest method (which is why we also log the element to see why this happens) ## Testing Instructions (or ideally a Blueprint) Hard to figure out, sometimes it occurs. --------- Co-authored-by: Adam Zieliński <[email protected]>
1 parent e9e36d6 commit ef999c5

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

packages/playground/remote/src/lib/playground-mu-plugin/0-playground.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ function playground_add_target_blank_to_external_links() {
100100
if (empty($_SERVER['REQUEST_URI']) || wp_doing_ajax() || wp_doing_cron()) {
101101
return;
102102
}
103-
103+
104104
?>
105105
<script>
106106
function addTargetBlankToExternalLinks() {
@@ -116,18 +116,26 @@ function addTargetBlank(a) {
116116
document.querySelectorAll('a[href]').forEach(a => {
117117
addTargetBlank(a);
118118
});
119-
119+
120120
// Set target="_blank" for external links when clicked.
121121
// This covers links that are added after the page has loaded.
122122
document.addEventListener('click', e => {
123-
const a = e.target?.closest('a[href]');
123+
// window, document, SVG Text nodes etc. don't have the `closest` method
124+
if ( !e.target?.closest ) {
125+
return;
126+
}
127+
const a = e.target.closest('a[href]');
124128
if (!a) return;
125129
addTargetBlank(a);
126130
});
127131

128132
// Also handle focus events to cover keyboard navigation on
129133
// links that are added after the page has loaded.
130134
document.addEventListener('focus', e => {
135+
// window, document, SVG Text nodes etc. don't have the `closest` method
136+
if ( !e.target?.closest ) {
137+
return;
138+
}
131139
const a = e.target?.closest('a[href]');
132140
if (!a) return;
133141
addTargetBlank(a);

0 commit comments

Comments
 (0)