From Colorant Iguana, 4 Weeks ago, written in JavaScript.
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>Test of preventDefault</title>
  7. <script>
  8. // Get the document for the content inside the iframe:
  9. function contentDoc() {
  10.     var iframe = document.getElementById("maincontent");
  11.     return iframe.contentDocument || iframe.contentWindow.document;
  12. }
  13.  
  14. // Populate the iframe when the enclosing page first loads:
  15. function fill_iframe() {
  16.     contentDoc().body.innerHTML = "<h1>Some Content</h1>"
  17.         + "<p>Here is a link that you're allowed to go to: <a href='https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker'><b>Caching files with Service Worker</b></a>"
  18.         + "<p>Here is a link that I don't want you to see: <a href='https://www.w3schools.com/jsref/event_preventdefault.asp'><b>Event preventDefault</b></a>";
  19. };
  20.  
  21. function iframe_onload() {
  22.     iframedoc = contentDoc();
  23.  
  24.     iframedoc.addEventListener('click', click_in_content);
  25. }
  26.  
  27. async function click_in_content(e) {
  28.     console.log("Click in iframe content!");
  29.     // e.target.matches('a') doesn't work reliably, so:
  30.     var target = e.target.closest('a');
  31.  
  32.     // The next two lines cause the problem. If they're here,
  33.     // then when you click on the second link, you'll see the
  34.     // "Calling preventDefault" but it doesn't actually preventDefault,
  35.     // but tries to go to the forbidden page.
  36.     // It doesn't seem to matter whether the named cache exists or not.
  37.     var cache = await caches.open("my-cache-name");
  38.     await cache.match(target);
  39.  
  40.     if (target) {
  41.         console.log("Click is over an a tag, href =", target.href);
  42.         if (target.href.endsWith("event_preventdefault.asp")) {
  43.             console.log("Calling preventDefault");
  44.             e.preventDefault();
  45.             return false;
  46.         }
  47.         console.log("Not calling preventDefault");
  48.     }
  49. }
  50.  
  51. </script>
  52. </head>
  53.  
  54. <body onload="fill_iframe();">
  55.  
  56. <h1>Test of preventDefault</h1>
  57.  
  58. <p>
  59. Here is an iframe:
  60. <iframe id="maincontent" width="90%" height="60%" onload="iframe_onload();">
  61.  
  62. </body>
  63. </html>
  64.  
captcha