From 556860a2fdc6a841f4dccb693e3f91ce205c34a0 Mon Sep 17 00:00:00 2001
From: Ella <ella@vandurpe.com>
Date: Thu, 7 Nov 2024 16:35:46 +0100
Subject: [PATCH] Prevent link clicks

---
 .../src/components/iframe/index.js             | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/packages/block-editor/src/components/iframe/index.js b/packages/block-editor/src/components/iframe/index.js
index e55a1fed9c627f..d1b0c44974951d 100644
--- a/packages/block-editor/src/components/iframe/index.js
+++ b/packages/block-editor/src/components/iframe/index.js
@@ -191,6 +191,24 @@ function Iframe( {
 				preventFileDropDefault,
 				false
 			);
+			// Prevent clicks on links from navigating away. Note that links
+			// inside `contenteditable` are already disabled by the browser, so
+			// this is for links in blocks outside of `contenteditable`.
+			iFrameDocument.addEventListener( 'click', ( event ) => {
+				if ( event.target.tagName === 'A' ) {
+					const href = event.target.getAttribute( 'href' );
+					if ( href.startsWith( '#' ) ) {
+						// Appending a hash to the current URL will not reload
+						// the page. This is useful for e.g. footnotes.
+						window.location.href = new URL(
+							href,
+							window.location.href
+						).toString();
+					} else {
+						event.preventDefault();
+					}
+				}
+			} );
 		}
 
 		node.addEventListener( 'load', onLoad );