Why can't I expand this event object in the chrome console?

前端 未结 4 2160
情深已故
情深已故 2021-01-01 16:54

Simplified, what I\'m doing is running this in the console:

window.onbeforeunload = function (e) {
    console.log(e);
}

But in the console

4条回答
  •  生来不讨喜
    2021-01-01 17:29

    This is happening because although you're letting the console persist over page changes, the Object no longer exists - it was destroyed when you left the page. This means it's simply not available to be inspected anymore, so clicking the down triangle is not helpful.

    Try this instead, to prevent the page actually changing:

    window.onbeforeunload = function (e) {
        console.log(e);
        return true;
    }
    

    Now the page will prompt to ask you what to do. Click 'cancel' in the prompt that comes up in order to remain on the page. Now you can inspect the Event in the console as desired.

    The difference is that the onbeforeunload function is now returning a value that isn't null/undefined. The return value could be anything, even '' or false, etc...anything except null and undefined, and it will still cause the page to prompt before navigating away and thus giving you an opportunity to inspect the event. Remember that with no return statement, JavaScript functions return undefined by default.

    Whenever you can't inspect something in the Chrome Dev Tools, 90% of the time it's because some action has caused that thing to become unavailable...the page has moved on from when that object existed.

提交回复
热议问题