简体   繁体   中英

adding an event listener to safari

I'm trying to add an event listener, via JavaScript for the Safari browser because it doesn't recognize the unload event of a window, apparently. So far I have:

function init()
{
//add unload event handler for safari
if (navigator.userAgent.toLowerCase().indexOf("safari")!=-1) {
    bodyElt = document.getElementsByTagName("body")[0];
     if (bodyElt) {
      bodyElt.addEventListener("unload", onUnloadHandler, false);
    }
}
...

Please do not use browser sniffing. The following is standards-compliant and works everywhere (if there is W3C DOM support; add wrappers as necessary):

    …

    <script type="text/javascript">
      function bodyLoad()
      {
        document.body.addEventListener("unload", onUnloadHandler, false);
      }
    </script>
  </head>

  <body onload="bodyLoad()">
    …
  </body>

…

Questions remain, though. Why are you not using the onunload attribute of the body element in the first place? And what do you need the unload event listener for? Many people think they need unload listeners because they do not handle closures properly, or have that misguided idea of trying to keep visitors at their site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM