ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 1.onbeforeunload 方法实现监听页面停留时间 ``` var dt1 = new Date(); window.onbeforeunload = function(){ var dt2 = new Date(); var ms = dt2.getTime() - dt1.getTime(); } ``` ## 2.解决微信iphone onbeforeunload 失效 ``` <html> <head> <meta charset="UTF-8"> <title>123</title> </head> <body> <div id="a"></div> <script> const KEY = 'duration'; let start = 0; // 记录开始时间 const data = localStorage.getItem(KEY); // 读取本地已经记录的时间 document.querySelector('#a').innerHTML = data || '空'; window.addEventListener('load', function() { start = Date.now(); }, false); window.addEventListener('unload', function() { const duration = Date.now() - start; localStorage.setItem(KEY, duration.toString()); }, false); </script> </body> </html> ``` ## 3.iphone不支持onbeforeunload ``` window.addEventListener("pageshow", myLoadHandler, false); window.addEventListener("pagehide", myUnloadHandler, false); function myLoadHandler(evt) { if (evt.persisted) { // This is actually a pageshow event and the page is coming out of the Page Cache. // Make sure to not perform the "one-time work" that we'd normally do in the onload handler. ... return; } // This is either a load event for older browsers, // or a pageshow event for the initial load in supported browsers. // It's safe to do everything my old load event handler did here. ... } function myUnloadHandler(evt) { if (evt.persisted) { // This is actually a pagehide event and the page is going into the Page Cache. // Make sure that we don't do any destructive work, or work that shouldn't be duplicated. ... return; } // This is either an unload event for older browsers, // or a pagehide event for page tear-down in supported browsers. // It's safe to do everything my old unload event handler did here. ... } if ("onpagehide" in window) { window.addEventListener("pageshow", myLoadHandler, false); window.addEventListener("pagehide", myUnloadHandler, false); } else { window.addEventListener("load", myLoadHandler, false); window.addEventListener("unload", myUnloadHandler, false); } ```