javascriptnode.jssocket.iochat

Prompting user if they want to leave the page


I'm building a web chat with sockets, and I recently added href support for urls like so: this is a test text measage with link
when the users click this link i want to prompt: Are you sure you want to open this link
but I'm not sure how to go about it


I could do
document.querySelectAll("a").[...]
but thats highly in inefficient 'cause new messages will be added and this has to be done every time to include all the ``.

How should I go about it?

Edit:

I'm specifying that: I do not want to use the browsers default

window.addEventListener("beforeunload"


Solution

  • As you add text to your chat, append it as an element (div?) so you can apply the event listener to the relevant HTMLElement. newDiv.querySelectorAll("a")...

    Better yet, use event delegation for using just 1 event handler for the container element.

    var container = document.querySelector(".container")
    container.addEventListener('click', function(ev) {
      if (ev.target.tagName == "A") {
        ev.preventDefault();
        var href = ev.target.href
        if (confirm("go to " + href + "?")) {
          console.log("do window.location = href here");
        }
      }
    });
    <div class="container">
      something with a <a href="https://example.com">link</a> that is preventDefault-ed
      <br> could have been added dynamically.
    </div>