javascript捕獲瀏覽器視窗關閉事件
阿新 • • 發佈:2019-02-07
為了防止使用者不小心關閉瀏覽器視窗,或者我們想在瀏覽器視窗關閉的時候做一些事,那麼我們會使用到window物件的onbeforeunload和onunload。
<script type="text/javascript"> showValue(); window.onbeforeunload = onbeforeunload_handler; window.onunload = onunload_handler; function onbeforeunload_handler(){ return "Are sure to leave?" } function onunload_handler(){ storeValue("hehehe"); } function showValue() { var localStorage = window.localStorage; alert(localStorage.getItem("key")); } function storeValue(value) { var localStorage = window.localStorage; localStorage.setItem("key",value); } </script>