Skip to content

Commit ba3e7d7

Browse files
authored
[Web] tolerate empty e.target in addTargetBlankToExternalLinks (#2555)
## Motivation for the change, related issues A user reported the following error coming from the `addTargetBlankToExternalLinks` function: ``` JavaScript Error: TypeError: e.target.closest is not a function https://playground.wordpress.net/scope:0.7531680412299814/wp-admin/post.php?post=5&action=edit:570:24 ``` It could happen when another event listener removes the `e.target` node before the event bubbles up to the `document` node. This PR makes sure an empty `e.target` is tolerated and short-circuits without an error. cc @draganescu
1 parent 55c1a82 commit ba3e7d7

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,15 +120,15 @@ function addTargetBlank(a) {
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+
const a = e.target?.closest('a[href]');
124124
if (!a) return;
125125
addTargetBlank(a);
126126
});
127127

128128
// Also handle focus events to cover keyboard navigation on
129129
// links that are added after the page has loaded.
130130
document.addEventListener('focus', e => {
131-
const a = e.target.closest('a[href]');
131+
const a = e.target?.closest('a[href]');
132132
if (!a) return;
133133
addTargetBlank(a);
134134
}, true);

0 commit comments

Comments
 (0)